简体   繁体   中英

Android socket client readUTF not working

I'm new to Java socket programming and I am doing a basic socket communication between an Android client and a Java server on the PC side. The server could receive the message from the client, but the client seems to have trouble reading messages from the server. I've been wondering why this is happening.

Server:

while(true){
   try {
    socket = serverSocket.accept();

    dataInputStream = new DataInputStream(socket.getInputStream());
    System.out.println("ip: " + socket.getInetAddress());
    System.out.println("message: " + dataInputStream.readUTF());

    dataOutputStream = new DataOutputStream(socket.getOutputStream());
    dataOutputStream.writeUTF("Hello Client !!!!!!" + "\n");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
...
...

   if (socket != null){
    try{
        socket.close();
        socket = null;
    }
    catch(Exception e){
        e.printStackTrace();
    }
}
}

Client:

socket = new Socket(serverIP, 8080);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(textOut.getText().toString());

dataInputStream = new DataInputStream(socket.getInputStream());
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        try {
            Log.i(TAG, dataInputStream.readUTF());
            textIn.setText(dataInputStream.readUTF());
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    });

On server side everything works fine but the Android client just can't receive the data. readUTF does not return anything (also returns a W/System.err in the logcat)

Solution:

I finally resolved the problem by moving the dataInputStream.readUTF() out of the runOnUIThread section. eg. Store it in a temporary string before runOnUiThread. I guess this should be a noob mistake.

Also calling readUTF() in a row was definitely stupid enough.

the Android client just can't receive the data

Your client tries to read two messages, but only one is sent.

Also your server never closes the connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM