我在java中制作了一个视频会议应用程序。它应该基于UDP。它在局域网上运行良好。现在我将其切换到WAN。经过大量关于NAT后UDP传输问题的阅读(因为不同路由器背后会有用户)。我尝试将孔打孔实现为读取。但它不起作用。我正在使用客户端 - 服务器 - 客户端架构。更确切地说,每个客户端将其图像(或帧)发送到服务器,然后服务器将它们转发给其他客户端。为此,我使用路由器为其分配的客户端IP和端口。然后,服务器将数据包发送给客户端。但是路由器仍然阻止了数据包。谁能告诉我什么应该是一个可靠的解决方案呢?或者有任何库可以有效地实现打孔?
==================================================================================
client code:
//some code
final Socket client = new Socket(IPaddr, port); // tcp connection
...
// code for some gui components...
...
String message2="video";
clientSocketReceiver = new DatagramSocket();
String ip = "x.x.x.x";
InetAddress IPAddress = InetAddress.getByName(ip);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
baos1.write(message2.getBytes());
baos1.write('\n');
baos1.flush();
byte[] message2InByte = baos1.toByteArray();
baos1.close();
clientSocketReceiver.send(new DatagramPacket(message2InByte, message2InByte.length, IPAddress, 8876));
...
//some code....
...
//thread for receiving images..
while (true) {
byte[] receiveData = new byte[50000];
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
clientSocketReceiver.receive(receivePacket);
InputStream in = new ByteArrayInputStream(receivePacket.getData());
buffImage = ImageIO.read(in);
...
//code for displaying images on GUI
...
}
//==========================================================================
=========================================================================== =
server code:
//code for storing client's ip and port. runs only when a new client is accepted by tcp socket....
serverSocket=new DatagramSocket(8876); //declared at starting of code
while (checked==false ) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String data = new String(receivePacket.getData());
data = data.trim();
if (data.equals("video")) {
vx.add(receivePacket.getAddress().getHostAddress()); // storing ip
String tmp = "" + receivePacket.getPort();
vv.add(tmp); //storing port. vv and vx r vectors
checked=true;
}
}
======================================
//thread for receiving/sending images from/to clients
DatagramSocket serverSocket2 = new DatagramSocket(9876);
byte[] receiveData = new byte[50000];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket2.receive(receivePacket);
InputStream in = new ByteArrayInputStream(receivePacket.getData());
bImage = ImageIO.read(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bImaget, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
for (int i = 0; i < vx.size() && i < vv.size(); i++) {
serverSocket2.send(new DatagramPacket(imageInByte, imageInByte.length, InetAddress.getByName(vx.elementAt(i).toString()), Integer.parseInt(vv.elementAt(i).toString())));
}
}
=============================================