user3543469
user3543469

Reputation: 198

Connection closed before receiving a handshake response

i write a node program,and i encounter a big difficult.

the server side code is below:

var express=require("express");
var app=express();
var socketio=require("socket.io");
var server=require("http").Server(app);
var ws=socketio.listen(server);
app.use(express.static('public'));
app.listen(3000);
ws.on('connection',function(socket){
socket.on("message",function(msg){
    console.log("got:"+msg);
    socket.send('pong');
    });
});

the client side code is below:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>websocket echo</title>
</head>
<body>
<h1>websocket echo</h1>
<h2>latency:<span id="latency"></span>ms</h2>
<script>

var lastMessage;
window.onload=function(){
    //create socket

    var ws=new WebSocket("ws://127.0.0.1:3000");
    ws.onopen=function(){
        //send first ping
        ping();
    };
    // 监听Socket的关闭
    ws.onclose = function(event) {
        console.log('Client notified socket has closed',event);
    };
    ws.onmessage=function(ev){
        console.log("got:"+ev.data);

        document.getElementById("latency").innerHTML=new Date-lastMessage;
        ping();
    };
    function ping(){
        lastMessage= + new Date;
        ws.send("ping");
    }
}
</script>
</body>
</html>

there is the tip in chrome console: WebSocket connection to 'ws://127.0.0.1:3000/' failed: Connection closed before receiving a handshake response (index):16 Client notified socket has closed CloseEvent

Upvotes: 4

Views: 8594

Answers (1)

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30430

As mentioned in the comments this happens because socket.io should be connected with it's own client. You should either use websockets or socket.io on both sides.

Upvotes: 1

Related Questions