使用BackgroundWorker从客户端获取消息

时间:2013-09-12 14:47:52

标签: c# client-server backgroundworker

我有一个客户端 - 服务器应用程序需要从客户端接收消息。 这是开始在服务器上监听的代码:

    private void startListening(TcpListener lisener)
    {
        BackgroundWorker backgroundWorker = new BackgroundWorker();
        backgroundWorker.WorkerReportsProgress = true;
        backgroundWorker.DoWork += backgroundWorker_DoWork;
        backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
        backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
        backgroundWorker.RunWorkerAsync();
    }

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        string message = string.Empty;
        _socket = _lisener.AcceptSocket();
        connectionAcceptedEvent("Connection accepted from " + _socket.RemoteEndPoint);
        byte[] b = new byte[100];
        int k = _socket.Receive(b);
        for (int i = 0; i < k; i++)
        {
            message += Convert.ToChar(b[i]); // Message from client
        }
    }

这是服务器完成从客户端接收所有消息的事件。此时,我需要获取消息字符串:

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{

}

1 个答案:

答案 0 :(得分:4)

使用每个事件处理程序的参数的Result属性来执行此操作:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    //...
    e.Result = message;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    string message = e.Result as string;
    //...
}

在旁注中,将每个新角色一次一个地连接到message,这是一个非常糟糕的主意。您应该在那里使用StringBuilder来附加字符,而不是每次都创建一个全新的中间字符串。