简体   繁体   中英

Why is my simple networking program breaking?

So I am learning UDP networking using guides on the internet. I found a guide, mostly copy/pasted code, and it worked. So then I obviously wanted to expand on my own. I'm trying to make a simple thing that will give the server the clients mouse position and then the server will send back the exact same message to all caps. But for some reason it'll work perfectly for anywhere from 0-100ish times and then just stops. Here's my code:

Server:

public class Server implements Runnable {

    boolean running = false;
    long time;
    InetAddress IPAddress;
    int port;

    public static void main(String[] args) throws Exception {
        Thread th = new Thread(new Server());
        th.start();
    }

    public Server() throws Exception {
        DatagramSocket serverSocket = new DatagramSocket(9876);
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];

        System.out.println("Server started");
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        IPAddress = receivePacket.getAddress();
        port = receivePacket.getPort();

        System.out.println("Client connected at " + IPAddress);
        String send = "Connected!";
        sendData = send.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        serverSocket.send(sendPacket);
        serverSocket.close();

        time = System.nanoTime();
        running = true;
    }

    public void run() {     
        int x = 0;
        while(running) {
            if(System.nanoTime() > time + 60/(1e9)) {
                time = System.nanoTime();
                try { 
                    x++;
                    DatagramSocket serverSocket = new DatagramSocket(9876);
                    byte[] receiveData = new byte[1024];
                    byte[] sendData = new byte[1024];

                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    serverSocket.receive(receivePacket);
                    System.out.println("Received message");

                    IPAddress = receivePacket.getAddress();
                    port = receivePacket.getPort();

                    String sentence = new String(receivePacket.getData());
                    System.out.println("RECEIVED " + sentence);

                    String capSentence = sentence.toUpperCase();
                    sendData = capSentence.getBytes();

                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
                    serverSocket.send(sendPacket);
                    System.out.println("Sent message.");
                    System.out.println(x);
                    serverSocket.close();   
                } catch(Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
}

Client:

public class Client implements Runnable {

    boolean foundConnection = false;
    boolean running = false;        
    long time;

    public static void main(String[] args) throws Exception {
        Thread th = new Thread(new Client());
        th.start();
    }

    public Client() throws Exception {
        time = System.nanoTime();
        running = true;
    }

    public void run() {
        while(running) {
            if(System.nanoTime() > time + (60/1e9)) {
                time = System.nanoTime();

                try {
                    DatagramSocket clientSocket = new DatagramSocket();
                    InetAddress IPAddress = InetAddress.getByName("localhost");

                    byte[] sendData = new byte[1024];
                    byte[] receiveData = new byte[1024];

                    String send = "Mouse is at " + mouse();
                    sendData = send.getBytes();

                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
                    clientSocket.send(sendPacket);
                    System.out.println("Sent message.");

                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    clientSocket.receive(receivePacket);
                    System.out.println("Received message.");

                    String modSentence = new String(receivePacket.getData());
                    System.out.println("FROM SERVER: " + modSentence);
                    clientSocket.close();
                } catch(Exception e) {
                    System.out.println("Error"); 
                }
            }
        }
    }

    public static Point mouse() {
        return new Point((int)MouseInfo.getPointerInfo().getLocation().getX(), 
                (int)MouseInfo.getPointerInfo().getLocation().getY());
    }
}

Maybe it's because it's not syncd right and the server is sending a message before the client gets to the part of code where it checks for a message? I have no idea because I'm really new to this. I'd love a diagnosis of why this is happening and how to fix it! Sorry for messy code, I'm new to this and coding in general.

You're most likely running into synchronization issues due to the fact that you keep opening and closing the server socket. This creates a race condition between the client's send() and the server's DatagramSocket creation. If the client sends its packet before the server's socket is initialized, the server won't receive it, and just wait for it forever. This is known as a deadlock .

To avoid this issue, just keep the server's socket open. Open it when the Server object is initialized, and close when the server program ends. This way, datagrams sent by the client will be kept in the socket buffer until the server calls receive() .

On a different note, the Server's constructor and the run() method have a lot of duplicate code. Code duplication frequently leads to inconsistencies in the program's logic and therefore, bugs. Try to avoid copy-pasting code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM