我有一个需要从客户端接收消息的客户端 - 服务器应用程序。这是开始在服务器上监听的代码:
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)
{
}