Search code examples
javaif-statementudpdatagram

DatagramPacket Using in UDP


I am trying to use DatagramPacket in Java to communicate with server and client.

My goal is: when the client says: "Hello", the Server should respond with: "Hi, nice to meet you". So I use a if condition to achieve this.

However, when the input is "Hello", it seems like it skips the if condition (I already used the debug). I wonder why this happened? It seems too weird. Can anyone help me with this problem? Any help would be appreciated! Thanks!

Code :

Client:

public static void main(String[] args) {
        System.out.println("This is Server");
        DatagramSocket server = null;
        byte[] container = new byte[1024];
        try {
            server = new DatagramSocket(9998);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        DatagramPacket dPacket = new DatagramPacket(container, container.length);   
        try {
            while(true) {               
                server.receive(dPacket);
                byte[] datas = dPacket.getData();
                String temp = new String(datas);
                if (temp.equals("Hello")) {
                    System.out.println("Hi~!Nice to meet you!");
                }else if (temp.equals("How are you?")) {
                    System.out.println("I am good!");
                }else {
                    System.out.println("Have a good day");
                }
                if (temp.equals("exit")) {
                    break;
                }


            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        server.close();
    }

client:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("This is Client");
        try {
            DatagramSocket client = new DatagramSocket(8888);
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String input = "";
            while(!input.equals("exit")) {
                input = br.readLine();
                byte[] msg = input.getBytes();
                DatagramPacket dPacket = new DatagramPacket(msg, msg.length,new InetSocketAddress("localhost",9998));
                client.send(dPacket);
            }

            client.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Solution

  • Try the following when receiving data.

    byte[] datas = dPacket.getData();
    String temp = new String(datas, 0, dPacket.getLength());