UDP消息传递服务

时间:2015-03-14 18:04:16

标签: java sockets udp ip-address datagram

我必须创建一个程序,用于向/从远程IP地址发送和接收消息。所以基本上它应该模拟消息服务。在程序中,您必须输入IP地址,数据将被发送到该特定地址。目前,我可以发送但是在远程IP地址机上,没有收到任何内容,反之亦然。请你帮我理解它为什么不起作用。

public class UDPchat extends Thread
{
   private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   int port=1234;                             // port to send/receive datagrams on
   String remoteIPaddress= null;      // IP to send datagrams

   // constructor, parameter is command line parameters
   public UDPchat(String IPAdrr) throws Exception
    {

    System.out.println("chat program: IP address " + InetAddress.getLocalHost().toString() + " port " + port );

    start();        // start thread to receive and display datagrams
    // loop waiting for keyboard input, send datagram to remote IP                
    while(true)
      try
        {
        String s = in.readLine();                       // read a String
        System.out.println("Sending to " + IPAdrr + " socket " + port + " data: " + s);
        byte[] data = s.getBytes();                                     // convert to byte array
        DatagramSocket theSocket = new DatagramSocket();                // create datagram socket and the datagram
        DatagramPacket   theOutput = new DatagramPacket(data, data.length, InetAddress.getByName(IPAdrr), port);
        theSocket.send(theOutput);                                      // and send the datagram
        System.out.println("send everything");
        start();

       }
      catch (Exception e) {System.out.println("Eroor sending datagram " + e);
   // thread run method, receives datagram and display contents as a string
   public void run()                
        {
          try
              {
              // open DatagramSocket to receive 
              DatagramSocket ds = new DatagramSocket(port);
              // loop forever reading datagrams from the DatagramSocket
              while (true)
                 {
                 byte[] buffer = new byte[65507];   
                 // array to put datagrams in
                 DatagramPacket dp = new DatagramPacket(buffer, buffer.length); // DatagramPacket to hold the datagram
                 ds.receive(dp);
                 // wait for next datagram
                 String s = new String(dp.getData(),0,dp.getLength());        // get contenets as a String
                 System.out.println("UDP datagram length " + s.length()+ "  from IP " + dp.getAddress() + " received: " + s );
                 }
              }
          catch (SocketException se) {System.err.println("chat error " + se); }
          catch (IOException se) {System.err.println("chat error " + se);}
          System.exit(1);                                                       // exit on error
        }

public static void main(String args[]) throws Exception
{
    Scanner in = new Scanner(System.in);
    String remoteIPaddress = in.nextLine();
   UDPchat c=new UDPchat(remoteIPaddress);
}

}

1 个答案:

答案 0 :(得分:1)

首先,对于消息传递服务,您应该使用TCP 可靠性。

UDP用于实时通信,其中最新数据更为重要。

考虑到您的问题,可能是因为如果您的计算机位于不同的网络中,路由器会进行网络地址转换。

我相信您正在将数据包发送到正确的IP地址,但端口不正确。您可能发送数据包的端口是计算机的本地端口。 您需要将数据包发送到路由器(或外部端口)分配的端口。

当数据包通过路由器从计算机A进入计算机B时,路由器将计算机的本地端口映射到某个随机外部端口。

因此,如果计算机B需要向计算机A发送数据包,则计算机B需要通过路由器分配给计算机A的外部IP:端口进行回复。然后,路由器将其转发到计算机A的本地IP:端口。

我建议首先了解UDP映射是如何创建的 数据包通过网络内部或外部的路由器传播。

在使用TCP / UDP之前,请仔细阅读网络地址转换,UDP打孔等网络概念。

这些来源可能有所帮助:

Network Address Translation

How NAT works?

UDP Hole Punching

RFC 4787 NAT Behavioral Requirements UDP

RFC 5128 P2P across NAT

您也可以参考我对这些相同/类似问题的一些答案:

How to Send A UDP packet via public IP through NAT?

How to send an UDP message for an array of clients (java)

UDP Image transfer works depending on network