我将JSON对象转换为字符串,并将其发送到TCP服务器。
private static void sendJsonObject(JSONObject json)
{
try
{
Writer out = new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream(), StandardCharsets.UTF_8));
out.write(json.toString());
}
catch ( IOException e )
{
e.printStackTrace();
}
}
虽然我只能发送一个字符串;如果我两次调用write
,则服务器仅收到第一个字符串
private static void sendJsonObject(JSONObject json)
{
try
{
Writer out = new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream(), StandardCharsets.UTF_8));
out.write(json.toString());
out.flush();
out.write(json.toString());
}
catch ( IOException e )
{
e.printStackTrace();
}
}
如何发送许多不同的字符串?我想能够做到
sendJsonObject(obj1)
sendJsonObject(obj2)
sendJsonObject(obj3)
edit
对此进行重构,仍然有相同的问题,并且由于日志,套接字显示已连接,因为我读取了消息socket is connected
/**
* Continuously check for new JSON commands in the buffer.
*
* @param connectionSocket
*/
private void listenForCommands(Socket connectionSocket)
{
try
{
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream(),
StandardCharsets.UTF_8));
while ( true )
{
log("listening for command");
if(mConnectionSocket.isConnected())
{
log("socket is connected");
}
else
{
log("socket is not connected");
}
String commandString;
commandString = inFromClient.readLine();
if(null != commandString)
{
log("received command : " + commandString + "\n");
JSONObject commandObj = new JSONObject(commandString);
if ( null != commandObj.getString("command") )
{
processCommand(commandObj);
log("command processed");
}
}
}
}
catch ( IOException e )
{
e.printStackTrace();
}
catch ( JSONException e )
{
e.printStackTrace();
}
}
看起来我需要两个循环,一个循环检查缓冲区中是否有行,另一个循环遍历缓冲区中的行。此外,如果套接字关闭,readlines
将始终返回null。
/**
* Continuously check for new JSON commands in the buffer.
*
* @param connectionSocket
*/
private void listenForCommands(Socket connectionSocket)
{
try
{
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream(),
StandardCharsets.UTF_8));
// continuously check the buffer for lines
while(true)
{
String commandString;
// process each line as a separate command
while ( null != (commandString = inFromClient.readLine()))
{
log("received command : " + commandString + "\n");
JSONObject commandObj = new JSONObject(commandString);
if ( null != commandObj.getString("command") )
{
//processCommand(commandObj);
log("command processed");
}
}
}
}
catch ( IOException e )
{
e.printStackTrace();
}
catch ( JSONException e )
{
e.printStackTrace();
}
}