Search code examples
c#socketsasynchronousdisconnect

Close Client Socket on disconnect


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);
        }
    }
}

Solution

  • 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.