数据报套接字适用于不通过互联网的机器

时间:2016-03-02 23:00:20

标签: java sockets datagram

我正在尝试通过互联网发送数据报套接字。将XXXXXX替换为localhost时,这些程序可在本地计算机上运行。放置在不同的机器和不同的Web连接上时,它不起作用。有没有人遇到过这个?我已经为路由器设置了端口转发,它仍然无法正常工作。任何帮助,将不胜感激。谢谢。

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

class UDPServer
{
    public static void main(String args[]) throws Exception
       {
        System.setProperty("java.net.preferIPv4Stack" , "true");
          DatagramSocket serverSocket = new DatagramSocket(9876);
             byte[] receiveData = new byte[1024];
             byte[] sendData = new byte[1024];
             while(true)
                {  
                   System.out.println(" I am waiting to recieve something.");
                   DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                   serverSocket.receive(receivePacket);
                   System.out.println("I recieved something");                  
                   String sentence = new String( receivePacket.getData());
                   System.out.println("RECEIVED: " + sentence);
                                   //serverSocket.send(sendPacket);
                }
       }
} 

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

class UDPClient
{
    public static void main(String args[]) throws Exception
    {
       BufferedReader inFromUser =
          new BufferedReader(new InputStreamReader(System.in));
       DatagramSocket clientSocket = new DatagramSocket();
       InetAddress IPAddress = InetAddress.getByName("XXXXXXXXXX");
       byte[] sendData = new byte[1024];
        //byte[] receiveData = new byte[1024];
       String sentence = inFromUser.readLine();
        System.out.println(sentence);
       sendData = sentence.getBytes();

       DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
       clientSocket.send(sendPacket);

       clientSocket.close();
    }
} 

0 个答案:

没有答案