jM2.me
jM2.me

Reputation: 3969

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

Upvotes: 1

Views: 12415

Answers (3)

Stephen Cleary
Stephen Cleary

Reputation: 457462

I recommend a type of "poll" or "heartbeat" message, as described here.

Upvotes: 0

Misko
Misko

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

Chris Haas
Chris Haas

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

Related Questions