Node.js socket.io with websocket

I invite you to Node.js or websocket. I have a problem:

My HTML is:

<!DOCTYPE html> <html> <head> <title>test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <script> "use strict"; var gniazdo = new WebSocket('ws://localhost:3000'); gniazdo.onopen = function(){ console.log('Połączono'); }; gniazdo.onmessage = function(m){ console.log(m.data); }; </script> </body> </html> 

My Node.js code:

 var io = require('socket.io')(3000); io.on('connection', function(socket){ console.log('a user connected'); }); 

I have an error in the console:

 WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response 

Help plz :)

+5
source share
1 answer

Your client uses WebSockets, but Socket.IO has its own protocol (which can be transported via WebSockets, but it can also be transmitted using other protocols). Change the client to use the native Socket.IO client:

 <script src="https://cdn.socket.io/socket.io-1.1.0.js"></script> <script> 'use strict'; var gniazdo = io('ws://localhost:3000'); gniazdo.on('connect', function () { console.log('Połączono'); gniazdo.on('message', function (m) { console.log(m.data); }); }); </script> 
+7
source

Source: https://habr.com/ru/post/1204863/


All Articles