我写了一个节点程序,我遇到了很大困难。
服务器端代码如下:
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');
});
});
客户端代码如下:
<!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>
Chrome控制台中有提示: 与'ws://127.0.0.1:3000 /'的WebSocket连接失败:在收到握手响应(索引)之前连接已关闭:16 客户端通知套接字已关闭CloseEvent
答案 0 :(得分:0)
正如评论中所提到的那样,因为socket.io应该与它自己的客户端连接。你应该在两边都使用websockets或socket.io。