The socket connection is closed before receiving a response to establish a connection

I wrote the code for the socket from: source

My code is as follows.

var port = 8081;
var app = require('http').createServer();
var io = require('socket.io')(app);
app.listen(port);

io.on('connection', function (socket) {
    console.log("New user connected.");
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
});
console.log("server listening on: " + port);

But when I test it on here (ws: // localhost: 8081). I acknowledge ERROR: undefined DISCONNECTED

An error occurs in the console:

WebSocket connection to 'ws://localhost:8081/?encoding=text' failed: Connection closed before receiving a handshake response
+4
source share
1 answer

You need to use the socket.io client library, either get it from here , or refer to your CDN from your page as follows:

<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>

, , socket.io, socket.io http://<your-server-address>/socket.io/socket.io.js. :

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="http://localhost:8081/socket.io/socket.io.js"></script>
        <script>
            var socket = io('http://localhost:8081/');
            socket.on('news', function (data) {
                console.log(data);
                socket.emit('my other event', { my: 'data' });
            });
        </script>
    </head>
    <body>
    </body>
</html>

, websocket.org github.

+3

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


All Articles