socket server listening all the time

送分小仙女□ 提交于 2019-12-08 12:11:40

问题


The requirement is server socket should accept the client socket connection all the time (windows service application). Below is the code which works fine for several hours, but after sometime accept does not work at all. To keep the accept all the time, I also have thread which connects the server every 10 min. By this way I got to know that server socket has stopped after some time (several hours)

public void StartReceiveNotification()
{
    if (!isStarted)
    {
        try
        {
            byte[] bytes = new Byte[1024];
            var ips = Dns.GetHostAddresses(Dns.GetHostName());
            var myAddress = ips.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
            assigningIp = myAddress; 
            server = new TcpListener(myAddress, 11001);
            server.Start();

            AcceptSockets();
            isStarted = true;
        }
        catch (Exception ex)
        {
            logger.Error(ex);
        }
    }
}

private void AcceptSockets()
{
    try
    {
        while (true)
        {
            var acceptedSocket = server.AcceptSocket();
            var state = new StateObject { BufferSize = 6000, Socket = acceptedSocket };
            acceptedSocket.BeginReceive(state.Buffer, 0, state.BufferSize, 0, this.ReadCallback, state);
            acceptedSockets.Add(acceptedSocket);
        }
    }
    catch (Exception ex)
    {
        logger.Error(ex);// no exception but stops accepting socket
    }
}

internal ElapsedEventHandler SendKeepLiveCommand()// triggers every 10 min
{
    try
    {
        if (assigningIp != null)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(assigningIp, 11001);
            socket.Send(ASCIIEncoding.ASCII.GetBytes("keepAlive"));
            socket.Disconnect(false);
            socket.Dispose();
        }
    }
    catch (Exception ex)
    {
        logger.Error(ex);// get exception after several hours
    }
    return null;
}

回答1:


issue was server had vpn connection and it was using that ip address. when vpn connection lost server stopped listening.



来源:https://stackoverflow.com/questions/50554018/socket-server-listening-all-the-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!