У меня возникли проблемы с созданием простой системы Java UDP

#java #sockets #numbers #udp #sequence

Вопрос:

Порядковые номера не работают, так как значение 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;
            }
            
        }
    }

}
 

Кто-нибудь может понять, почему они будут сброшены, пожалуйста?

Комментарии:

1. Расплывчатое название. Перепишите, чтобы обобщить вашу конкретную техническую проблему.

Ответ №1:

Исключение, которое вы получаете, вызвано закрытием Scanner . Когда Scanner экземпляр закрыт, он закрывает базовый поток, который находится System.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