我正在尝试使用Android Studio及其模拟器在给定端口上创建简单的UDP连接。我能够使用在eclipse中运行的客户端/服务器来完成这项工作。
但是,当将代码移植到android中时,打开的端口是TCP。
以下是android代码:
@Override
public void run() {
// Perform our network ops in this loop, anything blocking really...
try {
Log.d(TAG, "UDP Connecting to " + HOST + " on port " + PORT);
datagramSocket = new DatagramSocket();
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
byte[] message = "UDP is da best".getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length, address, PORT);
datagramSocket.send(packet);
byte[] buffer = new byte[65536];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
while (true) {
datagramSocket.receive(incoming);
byte[] data = incoming.getData();
String s = new String(data, 0, incoming.getLength());
Log.d(TAG, "Client: " + incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " - " + s);
Thread.sleep(500);
DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , PORT);
datagramSocket.send(dp);
}
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
此代码几乎来自here
以下是创建为TCP的端口的图片:
答案 0 :(得分:0)
使用第一个更改端口解决了问题,5555正在使用中,127.0.0.1也不是要使用的ip,使用10.0.2.2让我连接并解决所有问题