1

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

    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)
{

}
4

1 回答 1

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那里来追加字符,而无需每次都创建一个全新的中间字符串。

于 2013-09-12T14:50:09.190 回答