发送和接收UDP数据包? [英] Sending and receiving UDP packets?

查看:96
本文介绍了发送和接收UDP数据包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个程序,可以将UDP数据包从客户端发送到服务器.

I have made a program to send an UDP packets from a client to a server.

这是发射机代码:

import java.io.IOException;
import java.net.*;

public class JavaApplication9 {    
    public static void main(String[] args) throws UnknownHostException, SocketException, IOException  {
        // TODO code application logic here
        byte[] buffer = {10,23,12,31,43,32,24};
        byte [] IP = {-64,-88,1,106};
        InetAddress address = InetAddress.getByAddress(IP);
        DatagramPacket packet = new DatagramPacket(
                buffer, buffer.length, address, 57
                );
        DatagramSocket datagramSocket = new DatagramSocket();
        datagramSocket.send(packet);
        System.out.println(InetAddress.getLocalHost().getHostAddress());
    }
}

接收方代码功能是这样的:

The receiver code function is this:

public void run() {
    try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        byte[] sendData = new byte[8];

        while (true) {
              DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData());
              System.out.println("RECEIVED: " + sentence);
              InetAddress IPAddress = receivePacket.getAddress();
              String sendString = "polo";
              sendData = sendString.getBytes();
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
              serverSocket.send(sendPacket);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我使用了Wireshark程序. UDP数据包在接收方的Wireshark程序中被接收到,但是Java程序无法识别它,该程序仅继续侦听端口并且什么都没发生?

I have used the Wireshark program. The UDP packet is received in the Wireshark program at the receiver but the Java program wouldn't recognize it, the program just keeps listening to the port and nothing happens?

推荐答案

接收方必须将接收方的端口设置为与发送方DatagramPacket中设置的端口相匹配.要进行调试,请尝试侦听端口> 1024(例如8000或9000).港口< 1024通常由系统服务使用,并且需要管理员访问权限才能绑定到此类端口.

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

如果接收方将数据包发送到其正在侦听的硬编码端口(例如端口57),并且发送方在同一台计算机上,则您将创建到接收方本身的环回.始终使用数据包中指定的端口,以防万一生产软件在任何情况下都需要检查以防止这种情况.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

数据包无法到达目的地的另一个原因是发件人中指定的IP地址错误. UDP与TCP不同,即使地址不可访问并且发送者也不会收到错误指示,它也会尝试发送数据包.您可以通过在接收器中打印地址来进行检查,以防调试.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

在您设置的发件人中:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

但使用字符串形式的地址可能更简单:

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

换句话说,将目标设置为192.168.1.106.如果这不是接收者,那么您将不会收到该数据包.

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

这是一个可以工作的简单UDP接收器:

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              InetAddress IPAddress = receivePacket.getAddress();
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   IPAddress, receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

这篇关于发送和接收UDP数据包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆