while循环在等待消息时做些什么
答
while (true)
{
counter += 1;
Console.WriteLine("Waiting for connection...");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
参考:http://csharp.net-informations.com/communications/csharp-multi-threaded-server-socket.htm
UPDATE:,如果你想你的主线程是免费的,并创建另一个线程来等待连接阅读这篇文章:http://www.codeproject.com/Articles/463947/Working-with-Sockets-in-Csharp
String theMessageToReceive = Encoding.Unicode.GetString(bytes, 0, bytesRec);
while (senderSock.Available > 0)
{
bytesRec = senderSock.Receive(bytes);
theMessageToReceive += Encoding.Unicode.GetString(bytes, 0, bytesRec);
// Do something
}
答
首先,多个while循环不是多线程。 C#是一种通过代码从上到下工作的语言。 二:
//create new worker
public System.ComponentModel.BackgroundWorker worker;
// Start new thread
private void StartBackgroundWorker (...) {...}
//what should the worker do
private void worker_DoWork (...) {...}
//if the progress has changed while working
private void worker_ProgressChanged (...) {...}
//thread is finished
private void worker_RunWorkerCompleted (...) {...}
这些都是需要的所有方法(也许有点多)该任务。 但我认为你应该在学习C#的时候低一点。
你的问题的答案是:是的,这是可能的 –
你知道一个好方法怎么样? – George
如果你想做其他事情,直到你收到消息,那么你不想等待。你想得到通知(通过一个事件)。启动等待消息的侦听器线程,然后通过消息器发布。 –