Android 如何正确获取服务器消息
问题 我将消息“12345”从套接字服务器发送到客户端:Android 如何正确获取服务器消息,android,sockets,inputstream,Android,Sockets,Inputstream,问题 我将消息“12345”从套接字服务器发送到客户端: myPrintWriter.println("12345"); 之后,我在客户端上阅读了以下消息: int c; while ((c = inputStream.read( )) != -1) { byte[] buffer2 = new byte[1]; buffer2[0] = (byte) c; String symbol = new String(buffer2 , "UTF-8"); Strin
myPrintWriter.println("12345");
之后,我在客户端上阅读了以下消息:
int c;
while ((c = inputStream.read( )) != -1)
{
byte[] buffer2 = new byte[1];
buffer2[0] = (byte) c;
String symbol = new String(buffer2 , "UTF-8");
String symbolCode = Integer.toString((int)buffer2[0]);
Log.v(symbol, symbolCode);
}
Log.v("c == -1", "Disconnected");
我在日志中看到:
与
为什么?我想这是线路终止符号。我需要得到字符串“12345”或任何其他和下一个字符串正确。请帮帮我
如果使用bufferedReader.readLine(): 如果我发送消息速度慢:
> V/data(5301): -3#Leo#alone in the dark 11-12
> V/message(5301): Leo: alone in the dark 11-12
> V/data(5301): -3#Leo#cgh 11-12
> V/message(5301): Leo: cgh 11-12
> V/data(5301): -3#Leo#c
> V/message(5301): Leo: c 11-12
> V/data(5301): -3#Leo#x 11-12
> V/message(5301): Leo: x
> V/data(5301): -3#Leo#d 11-12
> V/message(5301): Leo: d
但如果我做得更快:
> V/data(5512): -3#Leo#fccc
> V/message(5512): Leo: fccc
> V/data(5512): -3#Leo#ccc
> V/data(5512): -3#Leo#cccc
> V/message(5512): Leo: ccc
> V/message(5512): Leo: cccc
> V/data(5512): --3#Leo#cccc //<-----error
> V/data(5512): 3-3#Leo#cccc //<-----error
> V/data(5512): #Leo#xdd
>V/data(5512):-3#Leo#fccc
>V/电文(5512):Leo:fccc
>V/数据(5512):-3#Leo#ccc
>V/数据(5512):-3#利奥#中交
>V/信息(5512):Leo:ccc
>V/信息(5512):Leo:cccc
>V/数据(5512):-3#Leo#cccc//V/数据(5512):3-3#Leo#cccc//V/数据(5512):#Leo#xdd
例外情况:(肯定是CR/LF。
这是因为您使用的是
println
。请尝试使用print
。请记住UTF-8
编码可能会导致每个字符超过一个字节,并且您上面的代码将无法正确处理它们
如果您想读取UTF-8
中编码的String
,最好使用“缓冲恐惧器”对其进行解码并逐行获取
示例代码:
String line;
BufferedReader _in = new BufferedReader(new InputStreamReader(_socket.getInputStream(),"UTF-8"));
try {
while ((line = _in.readLine()) != null) {
Log.d(TAG, line);
}
Log.d(TAG, "Connection is closed");
} catch (Exception e) {
Log.d(TAG, "Connection is closed");
}
关于。因此,当inputStream返回-1时,我看不到我的连接状态。我不确定是否理解您的评论,但使用上面的代码,当缓冲区中没有更多字符串时,您会得到
null
。如果您想检查连接状态,您仍然可以查看inputStream
或套接字
。是的,我不能,但我创建了一些问题:InputStream.read()从我的InputStream中删除第一个字节。我尝试将此字节与其他行连接,一切正常,但如果消息来得太快,由于某种原因,第一个字节不会与其他行连接。之后,我收到一个异常。抱歉,但我无法理解您的评论。我需要清楚您想要实现什么以及您到底是什么问题。我已经更新了我的答案,以说明如何测试连接关闭。
> V/data(5512): -3#Leo#fccc
> V/message(5512): Leo: fccc
> V/data(5512): -3#Leo#ccc
> V/data(5512): -3#Leo#cccc
> V/message(5512): Leo: ccc
> V/message(5512): Leo: cccc
> V/data(5512): --3#Leo#cccc //<-----error
> V/data(5512): 3-3#Leo#cccc //<-----error
> V/data(5512): #Leo#xdd
String line;
BufferedReader _in = new BufferedReader(new InputStreamReader(_socket.getInputStream(),"UTF-8"));
try {
while ((line = _in.readLine()) != null) {
Log.d(TAG, line);
}
Log.d(TAG, "Connection is closed");
} catch (Exception e) {
Log.d(TAG, "Connection is closed");
}