开发者

how to trace that client is disconnected?

开发者 https://www.devze.com 2023-02-22 01:33 出处:网络
In a client server application a client is connected to server, now if client disconnects then I want it must trigger an event on the server notifing that it is disconnected. I can achieve this using

In a client server application a client is connected to server, now if client disconnects then I want it must trigger an event on the server notifing that it is disconnected. I can achieve this using timer or some loop and a different thread. This thread continuously checks the connection of the client. That is it. But it is something like a polling mechanism. I want to write something like interrupt mechanism. I mean I don't want to use timer or loop. When a client disconnects willingly or unwillingly either from client side or server side my server should notify that client is disconnected. P开发者_JS百科lease dont tell about how to make custom events.

(I have asked the same question few minutes ago but could not find the response properly and question is closed by the forum...)


It's not clear whether you're talking about ASP.NET (or other web stuff), using sockets for direct communication, remoting, WCF or something else. Please clarify if you can.

It seems you're talking about polling vs. event-driven systems. The exact implementation and details depend on the question above. "Please dont tell about how to make custom events" doesn't make much sense: you don't seem to want to poll and depending on the situation, you might have to create a custom event.


Update given the fact you're working with sockets:

There are no events that are fired, with sockets it will simply be that a read, write, etc call will fail with a SocketException.

Please see here for more information:

Instantly detect client disconnection from server socket

You could create your own event for this, if your socket is handled in another thread for example, your thread method could look something like this:

bool running = true;
while (running)
{
    try
    {
        // do socket work here - read/write/etc
    }
    catch (SocketException)
    {
        // something happened, e.g. client disconnected. stop thread running.
        // you could fire your 'Disconnected' event here.
        running = false;
    }
}

Basically, when a client disconnects socket methods will throw SocketException, and you can check the SocketError property of the exception object for the reason. It will be one of these:

http://msdn.microsoft.com/en-us/library/system.net.sockets.socketerror.aspx

These results indicate a disconnected client: ConnectionReset, NotConnected ... but you'll pretty much have to write-off the whole socket if you get any SocketException.

0

精彩评论

暂无评论...
验证码 换一张
取 消