5

I'm begginer in Node.js or websocket. I have problem:

My HTML code:

<!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 error in console:

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

Help plz :)

1
  • Socket.io first tests the connection with long-polling and upgrades to websockets if they are supported. You need to use the socket.io client library. Commented Oct 16, 2014 at 20:30

1 Answer 1

7

Your client is using WebSockets, but Socket.IO has its own protocol (that may be transported over WebSockets, but it can also be transported over other protocols). Change your client to use Socket.IO's own 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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.