代码之家  ›  专栏  ›  技术社区  ›  Aqeel Ashiq

聊天应用程序。消息结尾字符应该是什么

  •  0
  • Aqeel Ashiq  · 技术社区  · 9 年前

    我正在用Java创建一个聊天应用程序。用户可以在一条消息中发送多个新行。以前,我不允许用户发送新行。因此,使用换行符作为消息结尾很容易。但现在我允许用户在消息中发送新行。我应该使用什么字符/字符串来标记消息的结尾。

    2 回复  |  直到 9 年前
        1
  •  0
  •   A M S Rejuan    9 年前

    通过添加额外的4字节,您可以轻松避免消息结尾。前4个字节表示消息的长度。然后添加完整消息。

    示例发件人代码:

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
    
        String msg = "its a test message";
        byte[] byteMsg = msg.getBytes();
    
        int length = byteMsg.length;
        byte[] lengthByte = ByteBuffer.allocate(4).putInt(length).array();
    
        byte[] finalMsg = new byte[length+4];
        System.arraycopy(lengthByte, 0, finalMsg, 0, 4);
        System.arraycopy(byteMsg, 0, finalMsg, 4, length);
    
        bufferedOutputStream.write(finalMsg);
    

    当您阅读消息时,请阅读前4个字节。将此4字节转换为整数。这是您的传入消息长度。然后解析这些字节。

        2
  •  0
  •   Amila    9 年前

    这是你的应用程序,所以你可以自由使用任何你喜欢的东西,包括 EOF NUL Marko和KDM建议的字符。

    只需确保您的用户不会在其消息中使用该字符。