简体   繁体   English

监听套接字仅监听一次

[英]Listen socket listens only once

I have a problem with my server socket code below - the loop in the Main() method is only executing once, never accepting any further input. 我下面的服务器套接字代码有问题Main()方法中的循环仅执行一次,从不接受任何其他输入。

class Server
{
    public Socket servSock(int Port)
    {
        Socket s1 = null;
        IPHostEntry ipHE = Dns.GetHostEntry("localhost");
        IPAddress ipA = ipHE.AddressList[0];
        IPEndPoint ipEp = new IPEndPoint(ipA, Port);
        s1 = new Socket(ipEp.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        s1.Bind(ipEp);

        return s1;
    }

    const int BUFFSIZE = 1024;
    const int BACKLOG = 255;

    static void Main(string[] args)
    {            
        Nwork nwork = new Nwork();
        Socket cl = null;
        Socket s = nwork.servSock(400);
        s.Listen(BACKLOG);

        byte[] rcvBuffer = new byte[BUFFSIZE];            

        for (; ; )
        {
            string text = "";

            Console.Clear();
            cl = s.Accept();                    
            Console.Write("Handling Client >> " + cl.RemoteEndPoint +"\n\n\n");
            cl.Receive(rcvBuffer, BUFFSIZE, SocketFlags.None);
            text = Encoding.ASCII.GetString(rcvBuffer, 0, BUFFSIZE).TrimEnd('\0');
            Console.Write(text);
            cl.Close();
        }
    }
}

Without deep diving in your code i would try adding the s.Listen(BACKLOG) in your for loop. 如果没有深入研究代码,我将尝试在for循环中添加s.Listen(BACKLOG)。
Note that this way you can only process i socket connection at the same time, if another person is gonna try and open a socket connection your process will be busy receiving the data from a previous connection. 请注意,通过这种方式,您只能同时处理套接字连接,如果另一个人要尝试打开套接字连接,则您的进程将忙于接收来自先前连接的数据。
It depends on your scenario but you might want to implement it asynchronous. 这取决于您的方案,但您可能要异步实现。
This link might be usefull if you decided to do so. 如果您决定这样做, 此链接可能会很有用。

I don't know what an "Nwork" is, but I suspect that's the source of your bug. 我不知道“ Nwork”是什么,但是我怀疑这是您的错误的根源。 Just initializing the socket manually works for me and allows subsequent connections. 手动初始化套接字对我来说是有效的,并允许后续连接。

static void Main(string[] args)
{
    Socket s = new Socket(SocketType.Stream, ProtocolType.TCP);
    Socket cl = null;
    System.Net.IPEndPoint endpoint = new System.Net.IPEndPoint(0, 400); // listen on all adapters on port 400
    s.Bind(endpoint);

    s.Listen(BACKLOG);

    byte[] rcvBuffer = new byte[BUFFSIZE];

    for (; ; )
    {
        string text = "";

        Console.Clear();
        cl = s.Accept();
        Console.Write("Handling Client >> " + cl.RemoteEndPoint + "\n\n\n");
        cl.Receive(rcvBuffer, BUFFSIZE, SocketFlags.None);
        text = Encoding.ASCII.GetString(rcvBuffer, 0, BUFFSIZE).TrimEnd('\0');
        Console.Write(text);
        cl.Close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM