使用 BackgroundWorker 从客户端获取消息
本文关键字:获取 消息 客户端 BackgroundWorker 使用 | 更新日期: 2023-09-27 18:31:14
我有一个客户端 - 服务器应用程序需要从客户端接收消息。这是在服务器上开始侦听的代码:
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)
{
}
使用每个事件处理程序的参数的 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
来附加字符,而不是每次都创建一个全新的中间字符串。