【问题标题】:How to get server message correctly如何正确获取服务器消息
【发布时间】:2012-11-13 10:26:52
【问题描述】:

问题

我从套接字服务器向客户端发送消息“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

例外:(

【问题讨论】:

    标签: android sockets inputstream


    【解决方案1】:

    请记住,UTF-8 编码可能会导致每个字符超过一个字节,您上面的代码将无法正确处理它们。

    如果您想读取以UTF-8 编码的String,最好让它们由“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");
        }
    

    问候。

    【讨论】:

    • 所以当 inputStream 返回 -1 时我看不到我的连接状态。
    • 我不确定我是否理解您的评论,但是使用上面的代码,当缓冲区中没有更多字符串时,您会得到null。如果要查看连接状态,仍然可以查看InputStreamSocket
    • 是的,我不能,但是我产生了一些问题:InputStream.read() 从我的 InputStream 中删除了第一个字节。我尝试将此字节与另一行连接,一切都很好,但如果消息来得太快,由于某种原因,第一个字节不会与另一行拼接。之后我收到一个异常。
    • 抱歉,我无法理解您的评论。我需要清楚你想要达到什么目标以及你的问题到底是什么。
    • 我已经更新了我的答案以展示如何测试连接关闭。
    【解决方案2】:

    肯定是 CR/LF。 它在那里是因为您使用的是println。请改用print

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多