[英]Converting sent byte array via socket to string
我正在使用通過套接字進行連接的小型LAN聊天應用程序。
如您在圖像上看到的,原始字節數組被錯誤地編碼為字符串。 我的猜測是在某處發生聯系。
發送:(這里不成問題)
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);
有什么想法嗎?
你得到多少個正方形?
我認為您要么發送一個太大的數組(“未填充”字節為零),要么在接收方創建這樣的數組。
調試您的應用程序! 您可以使用網絡終端程序通過TCP vor UDP手動發送數據。
我建議使用Sysinternals TCPView來監視連接和傳輸的數據量,並建議使用HWGroup Hercules作為網絡終端軟件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.