我想如何使用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());
}
答案 0 :(得分:1)
我认为你实际上可以遵循两条路径:
答案 1 :(得分:0)
您也可以使用Socket.poll命令。当poll返回true时,套接字if accept_able否则检查输入密钥,如果是Esc则终止。
例如:
do
{
// Poll use microseconds, waits 1 second
if (listener.Poll(1000000, SelectMode.SelectRead))
{
// the socket is accept/able
Socket handler = listener.Accept();
etc ...
}
//i wanna catch an Escape key here
ConsoleKeyInfo keyx = Console.ReadKey(true);
while (keyx.Key != ConsoleKey.Escape)
etc ...
} while (true);