Detect When user disconnects Socket TCP Asynchronous C#

Asked

Viewed 94 times

1

I am developing an Asynchronous TCP server in C#, but not how to make my system detect that the user disconnected or was disconnected for some reason and perform a procedure for removing it from the user list. My User object is currently like this:

public int id;
    public string name;
    private Socket _socket;

    private byte[] _buffet;



    public PlayerInfo playerInfo (){
        name = "";
        return new PlayerInfo (id, name);
    }

    public ClientInfo(Action<int, String> callback, Socket client){
        try{
            this.callback = callback;
            this._socket = client;
            this._buffet = new byte[this._socket.ReceiveBufferSize];
            this._socket.BeginReceive (this._buffet, 0, this._buffet.Length, SocketFlags.None, new AsyncCallback (receiveCallBack), null);
        }catch(Exception){

        }
    }

    public void Send(Message msg){
        if (this._socket.Connected) {
            try{
                byte[] buffer = SMS.Enconde.GetEncode().GetBytes(JsonConvert.SerializeObject(msg));
                this._socket.BeginSend(buffer,0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
            }catch(Exception){

            }
        }
    }

    private void SendCallBack(IAsyncResult IA){
        try{
            this._socket.EndSend(IA);
        }catch(Exception){

        }
    }

    private void receiveCallBack(IAsyncResult IA){
        try{
            int received = this._socket.EndReceive (IA);

            Array.Resize (ref this._buffet, received);
            String text = SMS.Enconde.GetEncode().GetString(this._buffet);

            Array.Resize (ref this._buffet, this._socket.ReceiveBufferSize);

            this._socket.BeginReceive (this._buffet, 0, this._buffet.Length, SocketFlags.None, new AsyncCallback (receiveCallBack), null);
        }catch(Exception){

        }
    }
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.