Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C#控制台应用程序中使用ReadKey()中断Socket.Accept()_C#_.net_Sockets - Fatal编程技术网

在C#控制台应用程序中使用ReadKey()中断Socket.Accept()

在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

我想知道如何用ReadKey()在同步服务器应用程序中中断Socket.Accept(),比如:当我按Esc或Ctr+X键时,它会自动停止套接字。根据一些阅读资料,我知道在调用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());
    }
套接字侦听器=新套接字(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.beginacept/Socket.EndAccept(EndAccept方法再次调用beginacept以处理多个客户端)。然后您的while循环可以调用Socket.Shutdown,当您的程序关闭要求得到满足时
  • 如果您不想使用BeginAccept/EndAccept(但我无法想象为什么),可以生成一个单独的线程来运行Socket.Accept,而主线程将等待适当的键组合,并再次调用Socket.Shutdown方法

  • 也可以使用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(),但控制程序执行的循环将独立运行。