简体   繁体   English

Android套接字客户端readUTF不起作用

[英]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. 我是Java套接字编程的新手,我正在Android客户端和PC端的Java服务器之间进行基本的套接字通信。 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. 在服务器端,一切正常,但Android客户端无法接收数据。 readUTF does not return anything (also returns a W/System.err in the logcat) readUTF不返回任何内容(还可以在logcat中返回W / System.err)

Solution: 解:

I finally resolved the problem by moving the dataInputStream.readUTF() out of the runOnUIThread section. 我终于通过将dataInputStream.readUTF()从runOnUIThread部分移出来解决了这个问题。 eg. 例如。 Store it in a temporary string before runOnUiThread. 将其存储在runOnUiThread之前的临时字符串中。 I guess this should be a noob mistake. 我想这应该是菜鸟的错误。

Also calling readUTF() in a row was definitely stupid enough. 连续调用readUTF()绝对足够愚蠢。

the Android client just can't receive the data Android客户端无法接收数据

Your client tries to read two messages, but only one is sent. 您的客户端尝试读取两条消息,但只发送了一条。

Also your server never closes the connection. 另外,您的服务器永远不会关闭连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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