4 ms·
Show HN: Socket-call – Call socket.io events like normal JavaScript functions
Hello HN,
I built a Typescript library (named socket-call, for lack of a more sexy name) whose goal is to be able to call socket.io events as regular functions.
So you declare your server-side like so:
...
const listenEvents = (services: UserServices) => ({
// Add your events here, the name of the event is the name of the function
login: async (username: string) => {
services._socket.data.user = { username };
console.log(`User ${username} logged in`);
setInterval(() => {
// Calling an event that's handled client-side
services.showServerMessage(`You're still logged in ${username}!`)
}, 1000);
return `You are now logged in ${username}!`;
},
});
and then on the client side you call them like normal async Javascript functions (and you can also create client-side event handlers):
...
const user = socket.addNamespace<UserEmitEvents, UserListenEvents>(
'/user'
);
// Calling an event that's declared server-side
user.login(username.value).then((message) => {
console.log('Server acked with', message);
});
// Handling an event that is sent by the server
user.showServerMessage = (message) => {
console.log('Server sent us the message', message);
}
I use this library for my own projects and would be interested to receive feedback about it :-)
- klabb3 1y agoThis appears to me like the NATS ”request-response” pattern. They also have first-class support for this in their client libs. Under the hood, they create and subscribe to an ephemeral topic where servers can send the response to. (Perhaps even streamed multiple responses but you’d need to double check that.) They also have websocket support btw, so it can be used by web browsers.
- chrisweekly 1y agoI like the ergonomics, this looks like it could be useful. Thanks for sharing!
- benpacker 1y agoYou can do with with trpc WebSocket transport
- dataviz1000 1y agotrpc has the benefit of being highly adopted, supported, and with a community.
- xixixao 1y agoConvex[0] also gives you type-safe persistence (in addition to type-safe web-socket communication). [0] https://docs.convex.dev/quickstart/script-tag https://docs.convex.dev/quickstart/script-tag
- ossobuco 1y agoI don't know, socket.io already feels like an unnecessary abstraction to me, and this is another abstraction on top of it. I generally dislike APIs that hide what's happening under "magic" abstractions, plus this seems leaky, as it abstracts on socket.io but requires you to know how it works.
- imtringued 1y agosocket.io is probably one of the most unnecessary libraries on this planet. Websockets are already as simple as possible. In fact, websockets work so well I use them as a generic TCP replacement, because the message oriented transport model gives me 99% of what I need with the exception of custom message types. Leaving that out was a massive letdown to me, because you now need to carry a way to identify the message type inside the body, rather than just throwing the message itself into the appropriate protocol parser (e.g. a schema based binary format).
- JonnyReads 1y agoI have to admit I've never tried to use web sockets without socket.io. Are they really as simple as you claim?
- efilife 1y agoSame here. I guess we'll just have to try It doesn't look difficult at all now I look at it https://javascript.info/websocket https://javascript.info/websocket
- korkybuchek 1y ago> socket.io is probably one of the most unnecessary libraries on this planet. Websockets are already as simple as possible. Eh... While I agree that socket.io is one of those libraries you could probably "write" in an afternoon, and Websockets are simple, there are a couple of things that are kinda painful to rewrite time after time: - keepalives to detect dead sockets - reconnection logic with backoff - ability to switch to long-polling for weird environments - basic multiplexing/namespacing
- dataviz1000 1y agoThat is awesome! I see you use Proxy which is a very cool way to achieve this. [0] I saw this approach using Proxy when hacking VSCode's ipc where they use it define services from ipc channels/ [1] I did something similar using VSCode's core ipc / rpc which only requires a transport (protocol) to implement {send, onMessage}. I use it in a Chrome extension so I have to implement my own socket.io and port message passing protocols. Some of the benefits are being able to send a message from MAIN world of an injected content script (if you want to intercept all fetch and XMLHttpRequest requests, for example) through a tunnel in the isolated world content script to the side panel which could theoretically tunnel it to a server over socket.io. If I have a Math service, for example, that only adds two numbers, it can be called from anywhere in the system with `await mathService.add(1,1);` with mathServer being dependency injected using constructor(@IMathService private readonly mathService: IMathService). This is how VSCode manages calling code across hundreds of different isolated JavaScript runtime environments. What I did was a bit overkill and likely trpc would have been good enough if I knew about it when I started. [0] https://github.com/bperel/socket-call/blob/e0076d7887397a92a2634fed27b574527d677169/client/index.ts#L216 https://github.com/bperel/socket-call/blob/e0076d7887397a92a... [1] https://github.com/microsoft/vscode/blob/24c0ff16c250f2b39eea8cebd661be2375f61ba5/src/vs/base/parts/ipc/common/ipc.ts#L1185 https://github.com/microsoft/vscode/blob/24c0ff16c250f2b39ee...