gpt4 book ai didi

java - 如何从套接字读取 JSON 数据而不是一行?

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:41 25 4
gpt4 key购买 nike

我的应用程序通过 WiFi direct 连接到传感器。然后它连接到套接字并应该读取数据。数据是 JSON,看起来像 {"d":{temp_mC";33416,"h​​umidity_ppm"...更多数据...}}。传感器每 2 分钟发送一次数据。之前我只能读取服务器发送的行,但由于传感器不发送行,我需要重做我的 TCPClient 类。我认为我可以实现此代码。

ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = socket.getInputStream().read(buffer)) != -1) {
result.write(buffer, 0, length);
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString("UTF-8");

要将 JSON 数据转换为字符串,然后我必须对其进行解析,但那是稍后的事。

我的旧代码看起来像这样,有人知道如何重新编写我的旧代码来实现上述方法或类似的方法,以便我可以读取 JSON 数据并将其转换为字符串以便稍后解析它吗?

TcpClient

public class TcpClient {

....

/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;

}

/**
* Sends the message entered by client to the server
*
* @param message text entered by client
*/

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

mRun = false;

mMessageListener = null;
mBufferIn = 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 {


//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));


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

mServerMessage = mBufferIn.readLine();

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.
socket.close();
}

} 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);
}

}

我在其他 Activity 中的 AsyncClass

  public class ConnectTask extends AsyncTask<String, String, TcpClient> {

@Override
protected TcpClient doInBackground(String... message) {

//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();

return null;
}

@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
CO2 = values[0];
//response received from server
Log.d("CO2", values[0]);
//process server response here....

}

}

最佳答案

处理这种情况的正确方法是一次发送整个数据。

可以通过首先发送数据大小,然后发送数据内容来实现,如下所示:

outputStream.writeInt(message.length); 
outputStream.write(message);

在读取消息时,解析长度,然后读取整个消息,如下所示:

int len = socketDataInputStream.readInt();                    
byte[] message = new byte[len];
socketDataInputStream.readFully(message, 0, message.length);

希望这有帮助,祝你好运。

关于java - 如何从套接字读取 JSON 数据而不是一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43325383/

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