我尝试在 Android 应用程序和服务器之间连续发送和接收 UDP 数据包。
有没有办法做到这一点?
我当前的网络代码(在线程中运行)如下所示。客户端通过3G连接。客户端配置的端口是 1088。
服务器在收到数据包时只是将数据包回显给客户端。服务器从客户端正确接收数据包,但客户端没有收到任何返回。
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.d(TAG, "S: Connecting...");
DatagramSocket socket = new DatagramSocket();
DatagramSocket receive_socket = new DatagramSocket(SERVERPORT, InetAddress.getByName("0.0.0.0"));
while(running) {
DatagramPacket packet_send = new DatagramPacket(msg, msg.length, serverAddr, SERVERPORT);
Log.d(TAG, "C: Sending: '" + new String(msg) + "'");
socket.send(packet_send);
// Prepare a UDP-Packet that can contain the data we want to receive
DatagramPacket packet = new DatagramPacket(buf, buf.length);
Log.d(TAG, "S: Receiving...");
// Receive the UDP-Packet
receive_socket.receive(packet);
Log.d(TAG, "S: Received: '" + new String(packet.getData()) + "'");
synchronized (this) {
wait(500);
}
}
我怀疑 3G 连接是 NATed(服务器报告的端口不同于 1088)。如果是这样,我能做些什么来克服它?或者我的代码有什么问题吗?