Subscribe and receive the latest tech updates, startup insights, and industry trends delivered straight to your inbox.
We respect your privacy. Unsubscribe at any time.
The article discusses the Socket Call library, which provides a simple and efficient way to establish WebSocket connections and handle real-time communication between clients and servers. The library aims to simplify the process of working with WebSockets, allowing developers to focus on their application logic rather than the complexities of the underlying WebSocket protocol.
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 :-)