hammerspoon icon indicating copy to clipboard operation
hammerspoon copied to clipboard

Is there any way to be notified when a client connects to a listening hs.socket?

Open jparoz opened this issue 2 years ago • 2 comments

I'm writing a little server in Hammerspoon which listens on a TCP socket, and forwards the received bytes to a USB MIDI device. The problem I have is that the client is a Hammerspoon script on another computer, which can connect/disconnect essentially at random times throughout the days and weeks that the server will be running. I need to know when the client connects (and possibly when it disconnects) to the server, so that I can start reading data from the socket. I can't see a way to do this though. Basically I want a version of connectCallback, but for a socket bound using hs.socket:listen, not hs.socket:connect.

Currently as a workaround I'm using hs.timer.waitUntil to wait until hs.socket:connected returns true. This works well enough, but it only checks every timer interval, which feels unnecessarily long; and then if the socket disconnects after that, I don't have a good way to restart the timer (except by using another timer, or having one timer running constantly).

Regarding implementation, it looks to me like the right place to call such a callback might be in didAcceptNewSocket? Happy to hear any input, or other workarounds. Thanks!

jparoz avatar Jun 08 '22 03:06 jparoz

As a workaround, you could add ping/pong messages that go between your client <> server, so you know when it's connected, and when it's timed out?

latenitefilms avatar Jun 08 '22 03:06 latenitefilms

I could, but then I'll have to implement some other way for the server to listen for the initial ping message from the client. Unless I'm misunderstanding what you're suggesting, I can't see any way to alert the server that a client has connected, aside from polling using hs.timer as I have been, or maybe using a UDP socket to initiate the connection as well. It just seems like something which should be possible without extra mechanisms, because the server socket object knows how many connections it has, and there's definitely code that runs when a new connection is created.

jparoz avatar Jun 08 '22 03:06 jparoz