如何获得服务器消息正确 [英] How to get server message correctly
问题描述
问题
我发送消息12345从插座服务器向客户端:
I send the message "12345" from the socket server to the client:
myPrintWriter.println("12345");
在我的客户端读取此消息:
After that I read this message on client:
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");
我在日志中看到了什么:
What I see in log:
通过
out.println("abcrefg");
为什么?我认为这是行终止符。我需要得到正确的字符串12345或任何其他和明年的字符串。请帮助我。
Why? I think it's line termination symbol. I need to get string "12345" or any other and next strings correctly. Help me please.
如果我使用bufferedReader.readLine():
If I use 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
但是,如果我做得更快:
But if I do it faster:
> 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
例外:(
推荐答案
在心目中的 UTF-8
enconding可能会导致每个字符多个字节,和你code以上将无法正确处理它们。
Have in mind the UTF-8
enconding may result in more than one byte per character, and your code above will fail to correctly handle them.
如果你想读字符串
连接$ C $在 UTF-8
CD,不如让他们德$由'BufferdReader` C $ CD和线得到它行。
If you want to read String
encoded in UTF-8
, is better to have them decoded by a ´BufferdReader` and getting it line by line.
举例code:
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");
}
问候。
这篇关于如何获得服务器消息正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!