我在两个独立的模拟器上运行了一个应用程序,我需要它们进行通信。 每个模拟器都需要发送或接收信息。
使用下面的类,例如,对于我将拥有的应用程序:
仿真器#1)Server-5554 接收端口= 9502,发送端口= 9503。
仿真器#2)Client-5556 接收端口= 9504,发送端口= 9505
然后我会在cmd中执行以下命令:
telnet localhost 5554
redir add udp:9503:9504
quit
telnet localhost 5556
redir add udp:9505:9502
quit
使用文档中的add <protocol>:<host-port>:<guest-port>
来自http://developer.android.com/tools/devices/emulator.html#redirection
然而,这不起作用。我不明白的一件事是你需要一个端口来发送和接收,但是文档只提供host:guest,但我认为host是它发送的端口,它被接收的guest端口重定向。我真的不明白这一点,例子会非常有帮助。
用于接收数据包:
public class ChatReceiverAsyncTask extends AsyncTask<Void, String, String> {
Context context;
ChatReceiverAsyncTask(Context context) {
this.context = context;
}
@SuppressWarnings("resource")
@Override
protected String doInBackground(Void... params) {
byte[] buffer = new byte[50];
DatagramSocket socket;
DatagramPacket packet;
String decoded = null;
try {
packet = new DatagramPacket(buffer, buffer.length);
socket = new DatagramSocket(9502);
socket.setReuseAddress(true);
while (true) {
socket.receive(packet);
decoded = new String(packet.getData(), "UTF-8");
System.out.println("Client recieved " + decoded);
publishProgress(decoded);
}
} catch (Exception e) {
e.printStackTrace();
}
return decoded;
}
用于发送数据包:
@Override
public void onCreate() {
try {
socket = new DatagramSocket(null);
socket = new DatagramSocket(9503);
socket.setReuseAddress(true);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void sendMessage(Message message, InetAddress destinationHost,
int port) {
try {
byte[] sendData = (message.sender + ": " + message.message)
.getBytes("UTF-8");
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, destinationHost, port);
socket.send(sendPacket);
Log.d("sendMessage", "sent packet");
} catch (Exception e) {
e.printStackTrace();
}
}