Java-如何在不进行端口转发的情况下将Datagram数据包发送到另一个网络?

时间:2019-01-23 18:26:26

标签: java networking server client datagram

我想用Java编写一个客户端服务器聊天程序,并且已经成功完成了该程序,但是我的程序仅在两台PC连接到同一网络时才起作用。

Client.java

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Client
{
    public static void main(String args[]) throws IOException
    {
        DatagramSocket sock = new DatagramSocket(1234);
        byte[] received = new byte[4096];
        String receivedata;     
        while(true)
        {           
            DatagramPacket packet = new DatagramPacket(received, received.length);
            sock.receive(packet);
            receivedata = new String(packet.getData());
            System.out.println(receivedata);
        }   
    }
}

Server.java

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Server
{
    public static void main(String args[]) throws IOException
    {
        byte[] send;
        String sendata = "Hello";
        send = new byte[sendata.getBytes().length];
        send = sendata.getBytes();
        InetAddress ip = InetAddress.getByName("192.168.42.158");
        DatagramSocket sock = new DatagramSocket();     
        while(true)
        {
            DatagramPacket sendpack = new DatagramPacket(send, send.length, ip, 1234);
            sock.send(sendpack);
        }
    }
}

我希望我的程序也可以在不同的网络上运行,并且我希望它不具有端口转发功能。

我搜索了VPN提供商可以完成的操作,但我不知道该怎么做。

请帮帮我!!!

0 个答案:

没有答案