通过套接字接收消息

时间:2009-03-30 18:14:55

标签: c# sockets

在c#模拟lan-messenger时,我正在使用环回地址来测试当前代码,并且能够接收我发送的第一条消息。但是之后没有任何消息到达套接字.Is有什么与清除套接字缓冲区有关吗?。请帮助 这是连接时的回调函数:

private void accepted(IAsyncResult iar)
    {
        Socket server = (Socket)iar.AsyncState;
        Socket client = server.EndAccept(iar);
        if (client.Connected)
        {
            try
            {
                client.BeginReceive(receive, 0, receive.Length, System.Net.Sockets.SocketFlags.None, new AsyncCallback(rec), client);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("arguments incorrect in begin-receive call", "Error", MessageBoxButtons.OK);
            }
            catch (SocketException)
            {
                MessageBox.Show("error in accessing socket while receiving", "Error", MessageBoxButtons.OK);
            }
            catch (ObjectDisposedException)
            {
                MessageBox.Show("socket closed while receiving", "Error", MessageBoxButtons.OK);
            }
            catch (Exception)
            {
                MessageBox.Show("error while receiving", "Error", MessageBoxButtons.OK);
            }

        }

这是执行begin-receive方法时的回调函数:

void rec(IAsyncResult ar)
    {

        StringBuilder receivedData;
        //String oldvalue;
        Socket remote = (Socket)ar.AsyncState;
        int recv = remote.EndReceive(ar);
        receivedData = new StringBuilder(Encoding.ASCII.GetString(receive, 0, recv));
        //MessageBox.Show(receivedData.ToString(), "received", MessageBoxButtons.OK);
        StringBuilder sb = new StringBuilder(this.textBox1.Text);
        sb.AppendLine(receivedData.ToString());
        if (textBox1.InvokeRequired)
        {
            this.Invoke((MethodInvoker)delegate { this.textBox1.Text = sb.ToString(); });

        }
        remote.Close(5);
        return;
    }

是否与stringbuilder或字符串数​​据类型有关,用于将收到的数据分配给变量。

3 个答案:

答案 0 :(得分:1)

这是一个关于C#套接字编程的两部分教程,包含源代码......

http://www.devarticles.com/c/a/C-Sharp/Socket-Programming-in-C-Part-I/1/

http://www.devarticles.com/c/a/C-Sharp/Socket-Programming-in-C-sharp-Part-II/

错误完全取决于您的设计。你在投票吗?或者,你在等待活动吗?

源是附加到此页面的download.zip文件: http://www.developerfusion.com/article/3918/socket-programming-in-c-part-1/

答案 1 :(得分:1)

看看这个。注意WaitForData如何调用自身。这允许接收第二个和后续消息。

您永远不会等待更多数据。

    private void OnClientConnect(IAsyncResult asyn)
    {
        m_Client = m_Listener.EndAccept(asyn);
        WaitForData();
    }
    private void WaitForData()
    {
        buffer = new byte[1024];
        m_Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
    }
    private void OnDataReceived(IAsyncResult asyn)
    {
        int iRx = 0;
        iRx = m_Client.EndReceive(asyn);

        if (iRx > 0)
        {
            PacketReceiver.BytesReceived(buffer);
        }

        if (m_Client.Connected == true)
            WaitForData();
    }

答案 2 :(得分:0)

您忘记在rec方法中调用BeginReceive:

以下是您的代码:

void rec(IAsyncResult ar)
{
  StringBuilder receivedData;
  //String oldvalue;
  Socket remote = (Socket)ar.AsyncState;
  int recv = remote.EndReceive(ar);
  receivedData = new StringBuilder(Encoding.ASCII.GetString(receive, 0, recv));
  //MessageBox.Show(receivedData.ToString(), "received", MessageBoxButtons.OK);
  StringBuilder sb = new StringBuilder(this.textBox1.Text);
  sb.AppendLine(receivedData.ToString());
  if (textBox1.InvokeRequired)
  {
    this.Invoke((MethodInvoker)delegate { this.textBox1.Text = sb.ToString(); });

  }
  remote.BeginReceive(receive, 0, receive.Length, System.Net.Sockets.SocketFlags.None, new AsyncCallback(rec), remote);
  //remote.Close(5);
  return;
}

当然这段代码不会关闭套接字而是等待更多数据。如果在send方法中为每条消息创建不同的套接字,则需要调用BeginAccept而不是BeginReceive。

希望有所帮助