Reputation: 3353
I'm trying to create WebSocket using the following code.
const express = require('express')
const app = express()
const http = require('http')
const server = new http.createServer(app)
const io = require('socket.io')(server)
const CONFIG = {
host: 'localhost',
port: 4444
}
io.on('connection', function (socket) {
const sid = socket.id
console.log('connection socket id:', sid)
for (const msg of ['disconnect', 'disconnecting', 'error']) {
socket.on(msg, data => {
console.log(`* ${msg}:`, data)
})
}
socket.on('join', data => {
console.console.log("data", data)
})
socket.on('signal', data => {
console.log('signal', data)
})
})
server.listen({
host: CONFIG.host,
port: CONFIG.port,
}, info => {
console.info(`Running on`, server.address())
})
When I try to test this using https://www.websocket.org/echo.html
I'm receiving an undefined error.
I have given ws://127.0.0.1:4444
in the location field but when I try to connect I'm getting the following error in the Log:
ERROR: undefined
and in the message Connection closed before receiving a handshake response
What is wrong here how I can make this working?
Upvotes: 2
Views: 62
Reputation: 5542
Your server seems good, you should implement the client yourself.
Socket.IO server and client example from the documentation.
Server:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
socket.on('message', (msg) => {
console.log('message: ' + msg);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Client (index.html):
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
var socket = io();
socket.emit('message', 'Test message.');
});
</script>
Upvotes: 1