Linh Nguyen
Linh Nguyen

Reputation: 51

UDP - Can't get data from DatagramPacket

I try to send and receive data between android and pc over UDP. This is code in 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();
    }
}

and code in 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();
    }
}

but output in pc is not "hello" like message in android code. This is my output: [B@462d5aee What should i do to fix it? Thanks!

Upvotes: 1

Views: 436

Answers (1)

user207421
user207421

Reputation: 310913

String data = new String(packet.getData());

That should be:

String data = new String(packet.getData(), 0, packet.getLength());

and

System.out.println(packet.getData().toString());

should be:

System.out.println(data);

Otherwise you are just printing byte[].toString() of an incorrect-length byte array.

Upvotes: 1

Related Questions