How to connect with socket.io from a ws client?

I have a very simple example of a socket.io socket, and the server-side code looks like this:

https://github.com/js-demos/socketio-chat-demo/blob/master/index.js

var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); app.use(express.static('public')); io.on('connection', function(socket){ socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); 

The client side uses the io socket code to connect it and works well:

https://github.com/js-demos/socketio-chat-demo/blob/master/public%2Findex.html

 <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> 

But I want to use another websocket client to connect the server, say wscat :

 npm install -g wscat wscat ws://localhost:3000 

But it cannot connect, with this error:

 error: Error: socket hang up 

Is my url ws://localhost:3000 wrong? How to make it work?

PS: You can see this project https://github.com/js-demos/socketio-chat-demo/ and try it

+7
source share
2 answers

In Chrome Dev Tools, I found the real websocket url, it should be:

 ws://localhost:3000/socket.io/?EIO=3&transport=websocket 

Using this url using wscat works well

+20
source

Agreeing with @freewind's answer, I would like to go a little deeper into the detailed description.

 ws://localhost:3000/socket.io/?EIO=3&transport=websocket 

The specification may be described as

 +----------------+--------------------+ | Elm | Desc | +----------------+--------------------+ | WS | scheme | | localhost:3000 | host | | socket.io | path | | EIO=3 | EngineIO version 3 | | transport | websocket | +----------------+--------------------+ 

If the transport value is set to websocket it can be websocket using any WebSocket client, since it updates the connection using the WebSocket protocol.

We can easily test and debug it using Firecamp WebSocket Client . The connection will look as follows.

Firecamp is a graphical client for SocketIO and WebSocket .

1. SocketIO

The configuration of the next screen will be similar

 import io from "socket.io-client"; const socket = io( "http://localhost:3000/socket.io", { "path": "/socketio", "transports": [ "websocket" ] } ); 

enter image description here

2. WebSocket

Same socket endpoint, we can test it with the WebSocket client, as shown in the following images

- WS connection enter image description here

- WS feed data enter image description here

0
source

All Articles