gpt4 book ai didi

java - 我的应用程序卡在 mBufferIn.readLine() 上

转载 作者:行者123 更新时间:2023-12-02 13:28:13 24 4
gpt4 key购买 nike

我一直在尝试将消息从服​​务器发送到我的应用程序。我正在使用应用程序“Simple Socket Tester”创建服务器并向应用程序发送 UTF-8 消息。我从未在我的应用程序上收到消息,当我调试应用程序时,它卡在“mServerMessage= mBufferIn.readLine();”行上并且永远无法超越它。所以看来它无法读取消息。当我暂停调试器时,我来到“LocalSocketImpl.java”,它卡在“私有(private) native FileDescriptor 接受”上。我可以做什么来防止这种情况发生?

我的 TCP 客户端:

public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;

}

/**
* Sends the message entered by client to the server
*
* @param message text entered by client
*/
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}


/**
* Close the connection and release the members
*/
public void stopClient() {

mRun = false;

if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}

mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}

public void run() {

mRun = true;

try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

Log.e("TCP Client", "C: Connecting...");

//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);

try {

//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
sendMessage("hi");

//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));



//in this while the client listens for the messages sent by the server
while (mRun) {

mServerMessage = mBufferIn.readLine();
System.out.println(mServerMessage);

if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}

}

Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");

} catch (Exception e) {

Log.e("TCP", "S: Error", e);

} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
}

} catch (Exception e) {

Log.e("TCP", "C: Error", e);

}

}

//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}

}

最佳答案

您收到的字符串末尾必须有“\n”。 readLine 方法将停止读取或等待流,直到读取“\n”。

关于java - 我的应用程序卡在 mBufferIn.readLine() 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43305163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com