简体   繁体   中英

Converting sent byte array via socket to string

I'm working on small LAN chat application where connection is via sockets.

问题

As you can see on the image, the original byte Array is badly encoded to string. My guess is that somwhere in connection somewhat happens.

Sending: (Here shuldnt be a problem)

           byte[] message = new byte[Encoding.UTF8.GetByteCount(txtPisanie.Text)];
            message = Encoding.UTF8.GetBytes(txtPisanie.Text);
            sck.Send(message);
            txtChat.Items.Add("Me: " + Encoding.UTF8.GetString(message));
            txtPisanie.Clear();

Async callback:

    int size = sck.EndReceiveFrom(aResult, ref epRemote);
            if (size > 0)
            {
                byte[] receiveData = new byte[((byte[])aResult.AsyncState).Length];
                receiveData = (byte[])aResult.AsyncState;
                string receivedMessage = Encoding.UTF8.GetString(receiveData);
                this.Dispatcher.Invoke((Action)(() => {
                    txtChat.Items.Add("Friend: " + receivedMessage);
                    Write("Friend: " + receivedMessage);
                }));
            }
            byte[] buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

Connection:

   epLocal = new IPEndPoint(IPAddress.Parse(txtIPLocal.Text), Convert.ToInt32(txtPortLocal.Text));
            sck.Bind(epLocal);

            epRemote = new IPEndPoint(IPAddress.Parse(txtIPRemote.Text), Convert.ToInt32(txtPortRemote.Text));
            sck.Connect(epRemote);

            byte[] buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

Initializing sockets:

        sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

Any thoughts about this?

How many squares do you get?
I think you either send a too large array, where the 'unfilled' bytes are zero, or you create such an array at the receiver side.
Debug your application! You can use network terminal programs to manually send data via TCP vor UDP.

I suggest Sysinternals TCPView to monitor the connection and the amount of transmitted data, and HWGroup Hercules as network terminal software.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM