我尝试通过UDP在android和pc之间发送和接收数据。 这是android中的代码:
String hostAddress = "10.0.2.2";
private static final int port = 2017;
DatagramSocket socket = null ;
InetAddress host;
String message = "hello";
@Override
public void run() {
try {
host = InetAddress.getByName(hostAddress);
socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), host, port);
socket.setBroadcast(true);
while(true){
socket.send(packet);
Thread.sleep(5000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
和pc中的代码:
DatagramSocket socket;
public final int port = 2017;
public ArrivedMessages(){
try {
socket = new DatagramSocket(port);
System.out.println( "Ready!") ;
byte inFromClient[];
inFromClient = new byte[256];
DatagramPacket packet = new DatagramPacket(inFromClient, inFromClient.length);
while(true){
socket.receive(packet);
String data = new String(packet.getData());
System.out.println(packet.getData().toString());
}
} catch (SocketException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
但是pc中的输出不像android代码中的消息那样“hello”。这是我的输出:[B@462d5aee
我该怎么做才能解决这个问题?谢谢!
答案 0 :(得分:0)
String data = new String(packet.getData());
应该是:
String data = new String(packet.getData(), 0, packet.getLength());
和
System.out.println(packet.getData().toString());
应该是:
System.out.println(data);
否则您只是打印一个不正确长度字节数组的byte[].toString()
。