模拟器中未收到来自本地主机的 UDP 数据包
我的应用在模拟器中运行时无法接收 UDP 数据包.UDP 数据包由以下 java 程序在localhost"上通过端口 49999 发送.
My app is unable to receive the UDP packets when running in the emulator. UDP packets are sent by below java program on "localhost" over the port 49999.
DatagramSocket clientsocket;
DatagramPacket dp;
BufferedReader br;
InetAddress ia;
byte buf[] = new byte[1024];
int cport = 50000, sport = 49999;
clientsocket = new DatagramSocket(cport);
dp = new DatagramPacket(buf, buf.length);
br = new BufferedReader(new InputStreamReader(System.in));
ia = InetAddress.getLocalHost();
while(true)
{
Random rand = new Random();
String str1 = rand.nextInt(100) + "";
buf = str1.getBytes();
System.out.println("Sending " + str1);
clientsocket.send(new DatagramPacket(buf,str1.length(), ia, sport));
try{
Thread.sleep(100);
} catch(Exception e){}
}
在同一本地主机上运行的另一个 java UDP 服务器程序可以正常接收数据包.这意味着数据包被正确发送到 localhost:49999.
Another java UDP server program running on the same localhost receives the packets fine. This means that the packets are sent to localhost:49999 correctly.
为了将数据包从本地主机转发到模拟器,我做了 telnet 重定向如下:
To forward the packets from localhost to the emulator, I did telnet redirect as below:
telnet localhost 49999
redir add udp:49999:49999
应用中的 UDP 接收器如下所示:
The UDP receiver in the app looks like this:
byte[] data = new byte[1400];
DatagramPacket packet = new DatagramPacket(data, 1400);
DatagramSocket socket = new DatagramSocket(49999);
socket.setSoTimeout(200);
try{
socket.receive(packet); ---->> This throws a SocketTimeoutException
} catch(SocketTimeoutException e){}
我的理解是 telnet 重定向应该负责将数据包从我的开发机器的 localhost:49999 转发到模拟器的 localhost:49999,以便数据在 DatagramSocket(49999) 上可用.但是它一直在抛出 SocketTimeoutException.
My understanding was that the telnet redirect should take care of forwarding the packets from my development machine's localhost:49999 to emulator's localhost:49999 so that the data is available on the DatagramSocket(49999). However it keeps throwing the SocketTimeoutException all the time.
知道这里缺少的拼图是什么会很有帮助.
It would be a great help to know what is the missing piece of the puzzle here.
推荐答案
连接到 localhost 后,您可能需要使用命令 netstat -na
检查端口是否按预期分配命令.改用 IP 127.0.0.1 也可能值得一试.
After connecting to the localhost you may want to check that the port was actually asigned as intended with the command netstat -na
in the cmd. It also might be worth a try to use the IP 127.0.0.1 instead.
相关文章