I have a very simple socket.io chat example, and the server side code is 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 using the socket io code to connect it and is working 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 some other websocket client to connect the server, say, wscat
:
npm install -g wscat
wscat ws://localhost:3000
But it can't connect, with this error:
error: Error: socket hang up
Is my url ws://localhost:3000
is wrong? How to make it work?
PS: You can see this project https://github.com/js-demos/socketio-chat-demo/ and try it
From the Chrome Dev Tools, I found the real websocket url, it should be:
ws://localhost:3000/socket.io/?EIO=3&transport=websocket
Use this url with wscat works well
Agreeing with @freewind 's answer, I would like to go little deeper with the detail description.
ws://localhost:3000/socket.io/?EIO=3&transport=websocket
The specification can be described as
+----------------+--------------------+
| Elm | Desc |
+----------------+--------------------+
| WS | scheme |
| localhost:3000 | host |
| socket.io | path |
| EIO=3 | EngineIO version 3 |
| transport | websocket |
+----------------+--------------------+
If the transport is set to websocket
then It can be testable with any WebSocket client as it's upgrading the connection with the WebSocket protocol.
We can easily test and debug it with the Firecamp WebSocket Client. The connection will look like this below image.
1. SocketIO
The configuration of the following screen will be like
import io from "socket.io-client";
const socket = io( "http://localhost:3000/socket.io",
{
"path": "/socketio",
"transports": [
"websocket"
]
}
);
2. WebSocket
The same socket endpoint, We can test it with the WebSocket client as showing in following images
- WS connection
- WS feed data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With