直接开搞!
首先,确认你已经安装过nodejs-websocket 模块,可以通过npm list查看已经安装过的modules;
没有安装?没有关系,进入nodejs的相应环境,nmp install nodejs-websocket 进行安装;
node服务端代码:websocket.js
var ws = require('nodejs-websocket');
console.log("开始建立连接...");
var server = ws.createServer(function (conn) {
conn.on("connect", function (code){
console.log("开启连接" + code);
});
conn.on("text", function (result) {
console.log("收到的信息为:" + result); //由Webtest.html中传来data
conn.sendText("success"); //发送"success"至Webtest.html
});
conn.on("close", function (code) {
console.log("关闭连接")
});
conn.on("error", function (code) {
console.log("异常关闭")
});
}).listen(8001);
console.log("WebSocket连接建立完毕");
html客户端代码:test.html
<!Doctype html>
<head>
<meta charset="UTF-8">
<title>WebSocket -- test</title>
</head>
<style>
.block {
text-align: center;
margin-top: 200px;
}
#mess {
text-align: center
}
.value {
width: 200px;
height: 200px;
border: 1px solid;
text-align: center;
line-height: 200px;
display: inline-block;
}
</style>
<body>
<div id="mess">正在连接...</div>
<div class="block">
<div class="value" id="value1">blcok-A</div>
<div class="value" id="value2">blcok-B</div>
<div class="value" id="value3">blcok-C</div>
</div>
<script>
var mess = document.getElementById("mess");
if (window.WebSocket) {
var ws = new WebSocket('ws://localhost:8001');
ws.onopen = function (e) {
console.log("连接服务器成功");
ws.send("route"); //可以传递信息,进行连接确认
}
ws.onclose = function (e) {
console.log("服务器关闭" + e.code); //服务器关闭1006
}
ws.onerror = function (e) {
console.log("连接出错" + e.code); //连接出错 undefined
}
ws.onmessage = function (e) {
mess.innerHTML = "连接成功";
console.log("node 返回信息: " + e.data); //若连接成功,为 success
document.querySelector(".block").onclick = function (e) {
var time = new Date();
ws.send(time + " 页面点击了“" + e.target.innerHTML + "”");
}
}
}
</script>
</body>
</html>
运行效果:
nodejs
浏览器