问题
Problem
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:

With
out.println("abcrefg");

Why? I think it's line termination symbol. I need to get string "12345" or any other and next strings correctly. Help me please.
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){...}
If I send messages slow:
> 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
Exception :(
回答1:
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.
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.
Example 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");
}
Regards.
回答2:
Definitely it is CR/LF.
It is there because you are using println
. Try print
instead.
来源:https://stackoverflow.com/questions/13359049/how-to-get-server-message-correctly