sono.land

connect

connect

WebSocket Connection

To establish a WebSocket connection, you will need to use sono.connect. Once the connect method is called, it will initiate the WebSocket handshake process. Data from the request object is necessary to complete the handshake between the server and client. A new instance of a client will be created with a unique ID. The client will then be added to the clients list that stores all clients currently connected to the server. If you are using the Channel feature, all new clients will enter the 'Home' channel by default. Connect will set up the sono WebSocket connection to listen to all incoming messages from the server. How the server will respond depends on the protocol of the incoming message. Protocols have been established on the Client side library.

To set up, first start your server with a specified port. Then create a new instance of the WebSocket API on the client side with a url such as 'ws://localhost:your port number/your endpoint'. This URL must be passed in as an argument when creating a new instance of SonoClient. When the server receives a request to upgrade to a WebSocket connection, sono.connect is invoked passing in the request and callback.

Client Side

1/* Example of creating a new instance of SonoClient which takes in the URL
2of the server using the WebSocket protocol.The end point in this
3particular example is 'ws'.
4 */
5const sono = new SonoClient('ws://localhost:8080/ws');
6sono.onconnection(()=>{
7 sono.message('client connected')
8})
9
10sono.on('message', (msg) => {
11 console.log('message received:', msg)
12})

Server Side

1const server = serve({ port: 8080 });
2const sono = new Sono();
3
4/* Our server is listening for incoming requests that is asking to
5 upgrade to a WebSockect connection. In this example we are waiting
6 for requests coming in through the ws protocol with the endpoint of
7 'ws'. */
8for await (const req of server) {
9 if (req.method === "GET" && req.url === "/ws") {
10 sono.connect(req, ()=> {
11 sono.emit('new client connected')
12 });
13 }
14}
Edit this page on GitHub