缓冲内存分配

时间:2012-12-25 15:47:31

标签: c# sockets memory-management garbage-collection buffer

我遇到缓冲区内存分配问题。我有两个线程的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值为零。

1 个答案:

答案 0 :(得分:1)

什么是buf.Length?行buf = new byte [1024]; //分配用于接收的内存让我困惑

您可以查看第一次运行时的尺寸吗?也许它的零?我没看到你在哪里宣布它,这就是为什么它困扰我。为什么不写var buf2 = new byte [1024];并将所有buf更改为buf2。实际上你不能简单地写byte [] buf而不是buf =?为什么它不起作用?它不能是编译错误吗?

- 是一个评论,但我有一种感觉,这可能会解决。如果不是这样的话我会删除 -