var ws = require("nodejs-websocket");
console.log("开始建立连接...");
// 创建 websocket服务器
ws.createServer(function(conn) {
// console.log(conn, "conn");
// 监听客户端发送过来的消息
conn.on("text", function(str) {
console.log("浏览器给服务端收到的信息为:" + str);
conn.sendText("服务器下发的内容=>" + str);
});
// 监听 关闭链接
conn.on("close", function(code, reason) {
console.log("关闭连接", code, reason);
});
// 监听 异常链接
conn.on("error", function(code, reason) {
console.log("异常关闭", code, reason);
});
}).listen(8001);
console.log("WebSocket建立完毕");
2. 客户端 inde.html代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>WebSocket</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
width: 96%;
margin-left: 2%;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="btn-group box" role="group" aria-label="...">
<button type="button" class="btn btn-default">Oppo</button>
<button type="button" class="btn btn-default">Vivo</button>
<button type="button" class="btn btn-default">Apple</button>
</div>
<div class="page-header">
<h5 class="info">服务器返回信息列表:</br></br></h5>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
if (window.WebSocket) {
// 创建对象 监听 8001端口
var ws = new WebSocket('ws://127.0.0.1:8001');
//监听 服务器链接成功
ws.onopen = function () {
console.log('连接服务器成功!');
ws.send('startting...');
}
// 监听服务器关闭
ws.onclose = function () {
console.log('服务器关闭');
}
//监听 链接出错
ws.onerror = function () {
console.log("连接出错");
}
//监听 服务端发来的消息
ws.onmessage = function (e) {
document.querySelector(".box").onclick = function (e) {
// 给服务器发送消息
ws.send('当前点击框的内容为:<font style="color:red;" >' + e.target.innerHTML + '</font>');
}
$('.info').append(e.data + '</br></br>');
}
}
</script>
</body>
</html>
发表评论