我在创建简单的 Java UDP 系统时遇到问题

I'm having trouble creating a simple Java UDP system

提问人:eroser534 提问时间:10/20/2021 最后编辑:President James K. Polkeroser534 更新时间:10/21/2021 访问量:86

问:

序列号不起作用,因为 int 值似乎重置为 0 - 或者在第二种方法中再次设置它返回错误。

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at Client3.sendThenReceive(Client3.java:106)
    at Client3.stopAndWait(Client3.java:69)
    at Client3.main(Client3.java:41)

这是客户端:

    import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.nio.*;


public class Client3 {
    
    private DatagramSocket datagramSocket;
    private InetAddress inetAddress;
    private byte [] buffer;
    private int initialSequenceNumber = 100;
    private int sequenceNumber;
    private int testSN;
    private static final int port = 1234;
    private static final int BUFFER_SIZE = 1024;
    private static final String HOSTNAME = "localhost";
    private static String message;
    
    public Client3(DatagramSocket datagramSocket, InetAddress inetAddress) {
        this.datagramSocket = datagramSocket;
        this.inetAddress = inetAddress;
    }

    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket();
        InetAddress inetAddress = InetAddress.getByName(HOSTNAME);
        Client3 client = new Client3(datagramSocket, inetAddress);
        System.out.println("Send datagram packets to a server");
        Scanner scanner = new Scanner(System.in);
        message = (scanner.nextLine() + " Umbrella");
        scanner.close();
        client.stopAndWait();

    }
    

    
    public void stopAndWait() throws IOException {
        Client3 client = new Client3(datagramSocket, inetAddress);
        sequenceNumber = initialSequenceNumber;
        ByteArrayOutputStream test = new ByteArrayOutputStream();
        DataOutputStream toSend = new DataOutputStream(test);
        toSend.writeInt(sequenceNumber);
        buffer = test.toByteArray();
        DatagramPacket testConnection = new DatagramPacket(buffer, buffer.length, inetAddress, port);
        System.out.println("testConnection sent, waiting for confirmation.");
        datagramSocket.send(testConnection);
        datagramSocket.receive(testConnection);
        ByteArrayInputStream confirmConnection = new ByteArrayInputStream(testConnection.getData());
        DataInputStream dis = new DataInputStream(confirmConnection);
        int SN = dis.readInt();
        //test code to show the received data to the console
        //System.out.println(SN);
        
        if (SN == sequenceNumber) {
            System.out.println("Confirmation received. Proceeding to Message delivery.");
            
            //testSN = sequenceNumber;
            //System.out.println("test: " + testSN + " SN: " + sequenceNumber);
            client.sendThenReceive();
        }
        else {
            System.out.println("error - incorrect sequence number.");
        }
    }
    
    public void sendThenReceive() {
        
        Scanner scanner = new Scanner(System.in);
        while (true) {
            try {
                
                // Changing the variable here results in error and termination
                //Is it because it is in the method?
                //int newNumber = 101;
                //testSN = 101;
                //sequenceNumber = 101;
                ByteArrayOutputStream test = new ByteArrayOutputStream();
                DataOutputStream toSend = new DataOutputStream(test);
                System.out.println("test: " + testSN + " SN: " + sequenceNumber);
                toSend.writeInt(sequenceNumber);
                toSend.writeUTF(message);
                buffer = test.toByteArray();
                System.out.println(message + "  " + sequenceNumber);
                
                DatagramPacket sentMessage = new DatagramPacket(buffer, buffer.length, inetAddress, port);
                datagramSocket.send(sentMessage);
                datagramSocket.receive(sentMessage);
                ByteArrayInputStream test2 = new ByteArrayInputStream(sentMessage.getData());
                DataInputStream dis = new DataInputStream(test2);
                int SN = dis.readInt();
                String messageFromServer = dis.readUTF();
                    if (SN == 101) {
                        System.out.println("The server says you said: " + messageFromServer);
                        sequenceNumber++;
                        Scanner newScanner = new Scanner(System.in);
                        message = (newScanner.nextLine() + " Umbrella");
                        newScanner.close();
                    }
                    else {
                        System.out.println("Error - incorrect sequence number.");
                    }
                
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        } scanner.close();
    }

}

这是服务器:

    import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.io.*;
import java.net.*;
import java.nio.*;

public class Server3 {
    
    private DatagramSocket datagramSocket;
    private byte[] dataForSend = new byte[256];
     byte[] receiveData = new byte[ dataForSend_SIZE ];
     //byte[] dataForSend = new byte[ dataForSend_SIZE ];
    private int initialSequenceNumber = 100;
    private int sequenceNumber;
    private static final int port = 1234;
    private static final int dataForSend_SIZE = 1024;
    
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(port);
        Server3 server = new Server3(datagramSocket);
        System.out.println("Server Operational");
        server.testConnection();
    }
    
    public Server3(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
        
    }

    public void testConnection() throws IOException {
    
        
        

         
         
         
         while (true) {
                try {
                    sequenceNumber = initialSequenceNumber;
                    DatagramPacket receivedMessage = new DatagramPacket (receiveData, receiveData.length);
                    datagramSocket.receive(receivedMessage);
                    InetAddress inetAddress = receivedMessage.getAddress();
                    int port = receivedMessage.getPort();
                                        
                    ByteArrayInputStream test = new ByteArrayInputStream(receivedMessage.getData());
                    DataInputStream dis = new DataInputStream(test);
                    int a10 = dis.readInt();
                  
                    System.out.println("SN read from Datagram: " + a10);
                    
                        if ( a10 == sequenceNumber) {
                            System.out.println("Connection Test Successfully Received.");
                            ByteArrayOutputStream confirmConnection = new ByteArrayOutputStream();
                            DataOutputStream toSend = new DataOutputStream(confirmConnection);
                            toSend.writeInt(sequenceNumber);
                            dataForSend = confirmConnection.toByteArray();
                            DatagramPacket testConnection = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
                            datagramSocket.send(testConnection);
                            System.out.println("'confirmConnection' has been sent.");
                            sequenceNumber++;
                            receiveThenSend();
                            }
                        else {
                            System.out.println("error - incorrect sequence number.");   }
        
    }
                
    
        finally {
            
        }
            }
         
     
}
    public void receiveThenSend() throws IOException {
        while (true) {
            try {
                sequenceNumber = 101;
                DatagramPacket sentMessage = new DatagramPacket(receiveData, receiveData.length);
                datagramSocket.receive(sentMessage);
                InetAddress inetAddress = sentMessage.getAddress();
                int port = sentMessage.getPort();
                ByteArrayInputStream test = new ByteArrayInputStream(sentMessage.getData());
                    DataInputStream dis = new DataInputStream(test);
                    int SN = dis.readInt();
                    System.out.println("SN received: " + SN);
                    System.out.println("SN on File: " + sequenceNumber);
                    String messageFromClient = dis.readUTF();
                                    
                if (SN == sequenceNumber) {
                    //String messageFromClient = new String(sentMessage.getData(), 0, sentMessage.getLength());
                    System.out.println("SN: Match.");
                    System.out.println("Message from Client: " + messageFromClient);
                    System.out.println("Response sent.");
                    ByteArrayOutputStream serverResponse = new ByteArrayOutputStream();
                    DataOutputStream toSend = new DataOutputStream(serverResponse);
                    toSend.writeInt(101);
                    toSend.writeUTF(messageFromClient);
                    dataForSend = serverResponse.toByteArray();
                    
                    sentMessage = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
                    datagramSocket.send(sentMessage);
                }
                else {
                    System.out.println("Error - incorrect sequence number.");
                }
                
                
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
            
        }
    }

}

谁能看出为什么这些会重置,请问?

Java 套接字 编号 UDP 序列

评论

1赞 Basil Bourque 10/21/2021
含糊不清的标题。重写以总结您的具体技术问题。

答:

0赞 Malt 10/21/2021 #1

您收到的异常是由关闭 .当实例关闭时,它会关闭底层流,在您的案例中。ScannerScannerSystem.in

因此,下次创建 时,它会在封闭的流上创建,并引发您看到的异常。Scanner.nextLine()

下面是重现该问题的代码片段:

Scanner s1 = new Scanner(System.in);
s1.close();
    
Scanner s2 = new Scanner(System.in);
s2.nextLine(); //Exception in thread "main" java.util.NoSuchElementException: No line found