C#异步套接字服务器只从客户端收到一条消息

时间:2016-02-27 16:01:29

标签: c# sockets asynchronous

我对套接字编程很新。我希望问题能够理解。

问题在于,当我使用客户端的button1_click发送textbox时 content - 服务器只获取第一条消息。我不知道出了什么问题。

可能是什么问题?

这是服务器:

    public partial class Form1 : Form
{
    Socket server;
    byte[] byteData = new byte[1024];

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            server = new Socket(AddressFamily.InterNetwork,
                                SocketType.Stream,
                                ProtocolType.Tcp);
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 20000);

            server.Bind(endPoint);
            server.Listen(1);
            server.BeginAccept(new AsyncCallback(Accept), null);
            textBox1.Text = "Server started...";
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Accept(IAsyncResult ar)
    {
        try
        {
            Socket client = server.EndAccept(ar);
            server.BeginAccept(new AsyncCallback(Accept), null);
            client.BeginReceive(byteData, 0, byteData.Length,
                SocketFlags.None, new AsyncCallback(Receive), client);

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Receive(IAsyncResult ar)
    {
        Socket client = (Socket)ar.AsyncState;
        client.EndReceive(ar);

        textBox1.Invoke(new Action(delegate ()
        {
            textBox1.AppendText(Environment.NewLine
                         + Encoding.ASCII.GetString(byteData));
        }));
        byteData = null;
    }
}

这是客户:

    public partial class Form1 : Form
{
    Socket client;

    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text == null)
            button1.Enabled = false;
        else
            button1.Enabled = true;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            client = new Socket(AddressFamily.InterNetwork,
                                SocketType.Stream,
                                ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipEndPoint = new IPEndPoint(ip, 20000);
            client.Connect(ipEndPoint);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {

            byte[] byteData = Encoding.ASCII.GetBytes(textBox1.Text);
            client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
                            new AsyncCallback(Send), null);
            textBox1.Text = String.Empty;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Send(IAsyncResult ar)
    {
        try
        {
            client.EndSend(ar);
        }
        catch (ObjectDisposedException)
        { }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Async中,只要您想收听消息,就必须在服务器端重新初始化BeginReceive

因此,在Receive回调中,您应该在BeginReceive之后重新启动EndReceive。否则你无法得到下一条消息:

private void Receive(IAsyncResult ar)
{
    Socket client = (Socket)ar.AsyncState;
    client.EndReceive(ar);
    client.BeginReceive(byteData, 0, byteData.Length, //add BeginReceive again
        SocketFlags.None, new AsyncCallback(Receive), client);

    textBox1.Invoke(new Action(delegate ()
    {
        textBox1.AppendText(Environment.NewLine
                     + Encoding.ASCII.GetString(byteData));
    }));
    byteData = null;
}

有关Async的更多工作示例,请查看以下内容:Sending a value from server to client with sockets