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

时间:2015-12-29 17:44:36

标签: c# wpf sockets

我正在开发连接通过的小型LAN聊天应用程序 套接字。

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

异步回调:

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

连接:

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

初始化套接字:

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

对此有何想法?

1 个答案:

答案 0 :(得分:1)

你得到了多少个方块?
我想你要么发送一个太大的阵列,那么“未填充的”#39; bytes为零,或者您在接收方创建这样的数组  调试你的应用!您可以使用网络终端程序通过TCP vor UDP手动发送数据。

我建议使用Sysinternals TCPView监控连接和传输数据量,并建议HWGroup Hercules作为网络终端软件。