我使用异步套接字创建了多个客户端服务器。每当我开始gui时,由于特定的代码服务器gui挂起的问题。以下是我的代码
static Socket serverSocket;
static byte[] buffer = new Byte[1024];
public static ManualResetEvent allDone = new ManualResetEvent(false);
private static void StartServer()
{
byte[] bytes = new Byte[1024];
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8001);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
serverSocket.Listen(100);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for.
Console.WriteLine("Waiting for a connection...");
serverSocket.BeginAccept(
new AsyncCallback(AcceptCallback),
serverSocket);
// Wait until a connection is made before tinuing.
allDone.WaitOne();
}
}
private static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
try
{
Socket clientSocket = serverSocket.EndAccept(ar);
//var buffer1 = new byte[1024];
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (Exception ex)
{
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
int received = 0;
Socket current = (Socket)ar.AsyncState;
Console.WriteLine("connected : " + current.RemoteEndPoint.ToString());
received = current.EndReceive(ar);
byte[] data = new byte[received];
if (received == 0)
{
return;
}
Array.Copy(buffer, data, received);
string text = Encoding.ASCII.GetString(data);
Console.WriteLine(text);
Send(current, "hello");
/// AppendToTextBox(text);
buffer = null;
Array.Resize(ref buffer, current.ReceiveBufferSize);
current.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), current);
}
catch (Exception ex)
{
}
}
}
每当我点击我的gui的按钮调用StartServer进程时gui挂起到期(true){}部分。控制台中的代码工作正常。避免这种情况的解决方案是什么?
答案 0 :(得分:1)
你可以这样做,否则你的gui线程必须等到无尽的 while循环结束;如果以下线程不是您想要的,请考虑添加中断函数。
using System.Threading;
Thread th = new Thread(new ThreadStart(delegate
{
//while loop
}));
th.Start();