joewalnes / websocketd

Turn any program that uses STDIN/STDOUT into a WebSocket server. Like inetd, but for WebSockets.
http://websocketd.com/
BSD 2-Clause "Simplified" License
17.14k stars 1.01k forks source link

How detect whet client disconnected #363

Closed ahvahsky2008 closed 4 years ago

ahvahsky2008 commented 5 years ago

When user connected to socket - i add data to db. I want delete this data when user is disconnected. How detect when connection is closed?

asergeyev commented 5 years ago

Process could handle "input closed", so where you read input you should have some sort of idea that client is no longer there.. Next step is handling SIGINT (unless you're on windows). You could catch it and do what your script needs for a cleanup. Next is SIGTERM but I would not recommend to perform any action there as you have two earlier opportunities that sound better.

Note that if you choose SIGINT route you should fit your actions in 100ms to quit avoid SIGTERM. If you could not fit into that time you should use --closems to add certain number of milliseconds to that period.

ahvahsky2008 commented 5 years ago

Can you share some examples ? I have more 5 years c# developing, but I don't understand what you mean

asergeyev commented 5 years ago

I have no idea about C# and how to do it there. I suppose to catch end of input you wrap your Console.ReadLine into try block and catch IOException later.

As signals go Windows is odd and I could not find any good example that I strongly feel works. Maybe someone else would mention way to do that.

ahvahsky2008 commented 5 years ago

What about python script?

asergeyev commented 5 years ago

I'd hope readline will throw exception on reading from closed stdin and so you can use it as "disconnect" event. But no, it's not that simple :))) Python returns empty line in readline so we need something like this for our "greeter" example:

diff --git a/examples/python/greeter.py b/examples/python/greeter.py
index dddf24e..6dcde01 100755
--- a/examples/python/greeter.py
+++ b/examples/python/greeter.py
@@ -9,6 +9,11 @@ from sys import stdin, stdout

 # For each line FOO received on STDIN, respond with "Hello FOO!".
 while True:
-  line = stdin.readline().strip()
-  print('Hello %s!' % line)
+  line = stdin.readline()
+  if line == '':
+    break
+  print('Hello %s!' % line.strip())
   stdout.flush() # Remember to flush
+
+
+# cleanup here, client disconnected

Hope it makes sense