我对C#和Sockets很陌生,但是我正在尝试制作一种“聊天”程序。我目前遇到的问题是让客户端能够自动从服务器接收消息(如果有的话)。
到目前为止我尝试过:
System.Threading.Thread myThread = new System.Threading.Thread(new
System.Threading.ThreadStart(listenThread));
public static void listenThread()
{
while(true){
Form1 form1 = new Form1();
form1.ReceiveLoop();
}
}
private void ReceiveLoop()
{
clientSocket.ReceiveTimeout = 100;
byte[] receivedBuffer = new byte[1024];
try
{
int rec = clientSocket.Receive(receivedBuffer);
byte[] data = new byte[rec];
Array.Copy(receivedBuffer, data, rec);
updateClient("Received: " + Encoding.ASCII.GetString(data));
}
catch (SocketException e)
{
//MessageBox.Show(e.ToString());
}
}
当我从GUI线程访问时,ReceiveLoop()工作,但是当通过myThread访问时,它将无法工作(由于超时而引发SocketException)。
我可以非常感谢任何有关我可以采取的方式的帮助或建议:D