问题
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