我遇到了缓冲内存分配的问题。我有两个线程的 WF 聊天应用程序:一个发送,一个接收。第一个客户端向服务器发送消息:
private async void send_button_Click(object sender, EventArgs e)
{
string msg = this.messageTextBox.Text.Trim();
await Task.Run(() =>
{
buf = Encoding.ASCII.GetBytes(msg); //buf-buffer for send/rcv
clientSock.SendTo(buf, servEP);
this.Invoke((Action)delegate
{
this.dialogTextBox.Text += string.Format("client: {0}",
this.messageTextBox.Text.Trim());
});
buf = new byte[1024]; //allocate memory for receiving
});
}
然后服务器响应,这里我遇到了缓冲区问题:
private async void Form1_Load(object sender, EventArgs e)
{
clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
servIPEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50000);
servEP = (EndPoint)servIPEP;
clientIPEP = new IPEndPoint(IPAddress.Any, 43000);
clientEP = (EndPoint)clientIPEP;
clientSock.Bind(clientEP);
while (true)
{
await Task.Run(() =>
{
//buf = new byte[1024] I tried to allocate here, but it's not working.
int rcv = clientSock.ReceiveFrom(buf, 0, buf.Length,
SocketFlags.None, ref servEP); // it returns right int value!
msg = Encoding.ASCII.GetString(buf, 0, rcv); //but buf is empty..
this.Invoke((Action)delegate
{
this.dialogTextBox.Text += rcv;
this.dialogTextBox.Text += string.Format("server: {0},rcv: {1}",
msg, rcv) + Environment.NewLine; //msg is empty...
});
});
}
}
这真的很奇怪,因为如果服务器重新发送消息,它在客户端接收没有问题。但第一条消息始终为空。事实上它收到了第一条消息,我测试过
int rcv = clientSock.ReceiveFrom(buf, ref servEP);
它返回正确的 int,但 buf 值为零。