我想知道如何使用 ReadKey() 中断同步服务器应用程序中的 Socket.Accept(),例如:当我按 Esc 或 Ctr+X 键时,它会自动停止 Socket。根据一些阅读,我知道在调用 Accept() 方法后,应用程序将被挂起,直到收到连接。cmiw
这是我的代码的一部分..
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("\t [wating connection from client...]");
//Based on msd doc, application will be suspend after this method
Socket handler = listener.Accept();
data = null;
//i wanna catch an Escape key here
ConsoleKeyInfo keyx = Console.ReadKey(true);
while (keyx.Key != ConsoleKey.Escape)
{
// Koneksi masuk yang di proses
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Message Received : {0}", data);
Console.WriteLine(handler.RemoteEndPoint.ToString());
// Memberikan balasan pada client
Console.Write("Your Reply : ");
String pesan = Console.ReadLine();
byte[] msg = Encoding.ASCII.GetBytes(pesan + "<EOF>");
handler.Send(msg);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}