TCP Client/Server 消息未正确发送

TCP Client/Server Messages Not Sending Properly

我刚开始使用 C# 处理与网络相关的事情,并且刚刚创建了一个 client/server 模型。我遇到的唯一问题是,当我发送数据时,部分数据被切断了。比如我发消息"Hello there!",它就发了"Hello".

示例:

我的服务器代码

    public static TcpClient tcpcl = new TcpClient();
    public static NetworkStream netstream;
    static void Main(string[] args)
    {
        while(!tcpcl.Connected)
        {
            try
            {
                tcpcl.Connect("127.0.0.1", 1234);
            }

            catch
            {

            }
        }
        netstream = tcpcl.GetStream();
        while(tcpcl.Connected)
        {
            byte[] buffer = new byte[tcpcl.ReceiveBufferSize];
            int unicodeData = netstream.Read(buffer, 0, tcpcl.ReceiveBufferSize);
            string plainText = Encoding.Unicode.GetString(buffer, 0, unicodeData);
            Console.WriteLine(plainText);

        }

        tcpcl.Close();
    }

我的客户端代码

    public static TcpListener tcpl = new TcpListener(IPAddress.Any, 1234);
    public static TcpClient tcpcl;
    public static NetworkStream netstream;
    static void Main(string[] args)
    {
        tcpl.Start();
        Console.WriteLine("Waiting for connection...");
        tcpcl = tcpl.AcceptTcpClient();
        netstream = tcpcl.GetStream();
        Console.WriteLine("Connection Established");
        while(tcpcl.Connected)
        {
            Console.WriteLine("Enter a message: ");
            string ptMessage = Console.ReadLine();
            netstream.Write(Encoding.Unicode.GetBytes(ptMessage), 0, ptMessage.Length);
            Console.WriteLine("Sent message");
        }
        tcpcl.Close();
    }

在您的客户端中,更改:

string ptMessage = Console.ReadLine();
netstream.Write(Encoding.Unicode.GetBytes(ptMessage), 0, ptMessage.Length);

收件人:

string ptMessage = Console.ReadLine();
byte[] bytes = Encoding.Unicode.GetBytes(ptMessage);
netstream.Write(bytes, 0, bytes.Length);

Write()的最后一个参数应该是返回的字节数组的长度,而不是原始字符串的长度。