简体   繁体   中英

Datagramsocket is not receiving

Hello everyone I am very new to java, I am trying datagramsocket send and receive packets. My client is sending packets, but server is not receiving. Please help me, Thanks in advance.
My client side code is as follows:

outString = "Hello World"  
InetAddress hostAddress = InetAddress.getByName("localhost");
buf = outString.getBytes();
DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 4002);
s.send(out);

My server side code is :

DatagramSocket sk = new DatagramSocket(PORT);
DatagramPacket dgp = new DatagramPacket(buf, buf.length);
sk = new DatagramSocket(PORT); //PORT is 4002
 while (true) {
    sk.receive(dgp);
    String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: "
      + dgp.getAddress() + ", port: " + dgp.getPort();
  System.out.println(rcvd);
}

This example works for me

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        byte[] buf = new byte[128];
        DatagramPacket dgp = new DatagramPacket(buf, buf.length);
        DatagramSocket sk = new DatagramSocket(PORT); //PORT is 4002
        while (true) {
            sk.receive(dgp);
            String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: "
                    + dgp.getAddress() + ", port: " + dgp.getPort();
            System.out.println(rcvd);
        }
    } else {
        String outString = "Hello World";
        InetAddress hostAddress = InetAddress.getByName("localhost");
        byte[] buf = outString.getBytes();
        DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 4002);
        DatagramSocket s = new DatagramSocket();
        s.send(out);
    }
}

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