Search code examples
c#.nettcpclient

TCP Client/Server Messages Not Sending Properly


I'm new to working with network-related things in C#, and have just finished created a client/server model. The only problem I'm having is that when I got to send data, part of it gets cut off. For example, I send the message "Hello there!", and it just sent "Hello".

Example:

image

My code for the server

    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();
    }

My code for the client

    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();
    }

Solution

  • In your client, change:

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

    To:

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

    The last parameter to Write() should be the length of the returned byte array, not the length of the original string.