问题
我将消息“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");
String symbolCode = Integer.toString((int)buffer2[0]);
Log.v(symbol, symbolCode);
}
Log.v("c == -1", "Disconnected");
我在日志中看到的内容:
用
out.println("abcrefg");
为什么?我认为这是行终止符号。我需要正确地获取字符串“12345”或任何其他和下一个字符串。请帮帮我。
如果我使用bufferedReader.readLine():
try
{
byte[] b1 = new byte[1];
int dataInt = clientSocket.getInputStream().read();
b1[0] = (byte)dataInt;
final String data;
if(dataInt == -1)
connectionIsLost();
if(dataInt != -1)
{
String c = new String(b1, "UTF-8");
data = c + inToServer.readLine();
}
else
data = inToServer.readLine();
if (data != null)
{
Log.v("data", data);
runOnUiThread(new Runnable()
{
//data parsing
});
}
}
catch (IOException e){...}
如果我发送消息慢:
> 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
例外:(
答案 0 :(得分:1)
绝对是CR / LF。
它就在那里,因为您正在使用println
。请改为print
。
答案 1 :(得分:1)
请记住,UTF-8
enconding可能会导致每个字符超过一个字节,并且上面的代码将无法正确处理它们。
如果您想阅读String
中编码的UTF-8
,最好让它们通过'BufferdReader`解码并逐行获取。
示例代码:
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");
}
问候。