简体   繁体   English

通过套接字将发送的字节数组转换为字符串

[英]Converting sent byte array via socket to string

I'm working on small LAN chat application where connection is via sockets. 我正在使用通过套接字进行连接的小型LAN聊天应用程序。

问题

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. 您可以使用网络终端程序通过TCP vor UDP手动发送数据。

I suggest Sysinternals TCPView to monitor the connection and the amount of transmitted data, and HWGroup Hercules as network terminal software. 我建议使用Sysinternals TCPView来监视连接和传输的数据量,并建议使用HWGroup Hercules作为网络终端软件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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