[NodeJS实战]NodeJS WebSocket实例
WebSocket服务端,在node中运行const WebSocket = require('ws');var wss = new WebSocket.Server({ port: 8181 });wss.on('connection', function (ws) {console.log('client connected');ws.on('message', function (data,
·
1. WebSocket服务端与客户端的建立
WebSocket服务端,在node中运行
const WebSocket = require('ws');
var wss = new WebSocket.Server({ port: 8181 });
wss.on('connection', function (ws) {
console.log('client connected');
ws.on('message', function (data, isBinary) {
console.log('Message from client ', isBinary?data:data.toString());
});
});
WebSocket 客户端,在node中运行
var ws = require("ws");
var sock = new ws("ws://localhost:8181/");
sock.on("open", function () {
console.log("connect success !!!!");
sock.send("HelloWorld");
});
sock.on("error", function(err) {
console.log("error: ", err);
});
sock.on("close", function() {
console.log("close");
});
sock.on("message", function(data) {
console.log(data);
});
WebSocket客户端,在浏览器中运行
var ws = new WebSocket('ws://localhost:8181');
ws.onopen = function(e){
console.log("连接服务器成功");
ws.send("what`s your name?");
}
ws.onclose = function(e){
console.log("服务器关闭");
}
ws.onerror = function(){
console.log("连接出错");
}
ws.onmessage = function(e){
let message = "message:" + e.data + "";
console.log(message);
}
以上代码保存为client_chrome.js文件,并在html文件中引用,如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文档标题</title>
<script type="text/javascript" src="client_chrome.js"></script>
</head>
<body>
<h1>我的第一个HTML页面</h1>
<p>我的第一个段落。</p>
</body>
</html>
在浏览器中运行以上html文件即可
2. WebSocket发送Json数据
发送Json数据
// 发送Json数据
var msg = {
"client":"control",
"url":"https://www.163.com"
}
var s = JSON.stringify(msg);//将Json对象转为字符串
console.log(s)
ws.send(s);
接收Json数据
ws.on("message", function(data, isBinary){
console.log("get msg: ", data.toString())
var msg = JSON.parse(data); // 字符串转Json对象
console.log("get client:", msg.client);
});
更多推荐
已为社区贡献3条内容
所有评论(0)