在C#控制台应用程序中使用ReadKey()中断Socket.Accept()
我想知道如何用ReadKey()在同步服务器应用程序中中断Socket.Accept(),比如:当我按Esc或Ctr+X键时,它会自动停止套接字。根据一些阅读资料,我知道在调用Accept()方法之后,应用程序将被挂起,直到收到连接为止。cmiw 这是我的部分代码在C#控制台应用程序中使用ReadKey()中断Socket.Accept(),c#,.net,sockets,C#,.net,Sockets,我想知道如何用ReadKey()在同步服务器应用程序中中断Socket.Accept(),比如:当我按Esc或Ctr+X键时,它会自动停止套接字。根据一些阅读资料,我知道在调用Accept()方法之后,应用程序将被挂起,直到收到连接为止。cmiw 这是我的部分代码 Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try
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());
}
套接字侦听器=新套接字(AddressFamily.InterNetwork,
流,ProtocolType.Tcp);
尝试
{
Bind(localEndPoint);
听(10);
while(true)
{
Console.WriteLine(“\t[等待来自客户端的连接…]”);
//基于msd文档,此方法后应用程序将暂停
套接字处理程序=listener.Accept();
数据=空;
//我想在这里拿一把逃生钥匙
ConsoleKeyInfo-keyx=Console.ReadKey(true);
while(keyx.Key!=ConsoleKey.Escape)
{
//杨迪散文集
while(true)
{
字节=新字节[1024];
int bytesRec=handler.Receive(字节);
data+=Encoding.ASCII.GetString(字节,0,bytesRec);
if(data.IndexOf(“”>-1)
{
打破
}
}
WriteLine(“收到的消息:{0}”,数据);
WriteLine(handler.RemoteEndPoint.ToString());
//Memberikan balasan pada客户
安慰。写下(“你的回答:”);
字符串pesan=Console.ReadLine();
byte[]msg=Encoding.ASCII.GetBytes(pesan+“”);
handler.Send(msg);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
我认为您实际上可以遵循两条路径:
也可以使用Socket.poll命令。当poll返回true时,如果可以接受,则套接字检查输入键,如果为Esc,则终止 对于exmaple:
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);
据我所知,BeginAccept()和EndAccept()是专门为异步模式构建的。我想让它成为同步模式,是为了教育目的。好的,第二个选项应该适合你。您仍将依赖synchronous Accept(),但控制程序执行的循环将独立运行。