Reputation: 3969
I have server application that listens for clients. Let's client lost internet connection and lost connection with server.
Does server automatically check when a client was disconnected? If not how may I implement such thing?
Main.cs http://pastebin.com/fHYpErz7
ServerSocket.cs: http://pastebin.com/erw4tzdp
Client.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace jM2
{
class Client
{
private int clientConnectionID;
private Socket clientSocket;
private string clientIP;
private byte[] clientBuffer = new byte[1024];
public Client(int connectionID, Socket connectionSocket)
{
clientConnectionID = connectionID;
clientSocket = connectionSocket;
clientIP = connectionSocket.RemoteEndPoint.ToString();
clientSocket.BeginReceive(clientBuffer, 0, clientBuffer.Length, SocketFlags.None, new AsyncCallback(dataArrival), null);
}
public void Disconnect()
{
clientSocket.Close();
}
private void dataArrival(IAsyncResult iar)
{
int bytesReceived = clientSocket.EndReceive(iar);
clientSocket.BeginReceive(clientBuffer, 0, clientBuffer.Length, SocketFlags.None, new AsyncCallback(dataArrival), null);
}
}
}
Upvotes: 1
Views: 12415
Reputation: 457462
I recommend a type of "poll" or "heartbeat" message, as described here.
Upvotes: 0
Reputation: 2044
Based on what Chris Haas said, I may be wrong, however I have previously written a TCP server and detected closed connections when I received 0 bytes. In other words, in your dataArrival method, if bytesReceived was 0, this would indicate the connection had closed. This seemed to work through fairly extensive testing.
Upvotes: 1
Reputation: 55457
See my answer to this question:
TcpClient.Close doesn't close the connection
Basically no one knows if the connection is closed until you try to send data. If it fails, the connection is closed.
Upvotes: 2