在 client-side & server-side 两端,使用 ws 时存在 API 写法上的差异,需要特别注意。
这边以监听和关闭连线来举例 :
// client
aWebSocket.onopen = function(event) {};
aWebSocket.onclose = function(event) {};
// server
ws.on('open', function () {});
ws.on('close', function () {});
虽然看起来很类似,但细微处仍有差异。
接着,测试对两端发送讯息,确认可以正常使用 ws 来连接两端。
server-side
// ...
wss.on('connection', function connection(ws) {
// reviced client-side
ws.on('message', function (msg) {
console.log(`server : ${msg}`);
});
// send to client-side
ws.send('Message from server');
});
client-side
// ...
<script>
const ws = new WebSocket('ws://127.0.0.1:3000');
// keep listen
ws.onopen = function () {
// send to server-side
ws.send('Hello Server!');
};
ws.onmessage = function (event) {
console.log(event);
};
</script>
打开 terminal 运行 server 底下的 index.js,前端页面则由 live-server 处理。
可以看到 server-side 发出文字讯息 Message from server
,并接收 client-side 送过来的 Hello Server!
。client-side 的页面会印出一个物件,其中的 data
则是保存 server-side 传输过来的资料。
在上一篇笔记中,有测试在 client 端的资料夹下使用 index.js 来接受和发送讯息,但这样容易搞混,所以统一 client-side 使用 websocket 的 api 写法,而 server-side 则使用 ws library 写法。并将 client/index.js -> main.js,同时将 index.html 的 script 移入。
client-side
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>This is Client</h1>
<script src="./main.js"></script>
</body>
</html>
// main.js
const ws = new WebSocket('ws://127.0.0.1:3000');
// keep listen
ws.onopen = function () {
// send to server-side
ws.send('Hello Server!');
};
ws.onmessage = function (event) {
console.log(event);
};
这是我第一次写铁人赛,我没有先规划大纲 所以运算子我就先写比较简单的部分,对於比较难的部分,後面有篇...
前言 现在我们要用我们之前学的内容, 做一个简单的 RecipeList APP。 实作 打开一个新...
现今的浏览器如 Firefox, Google Chrome 多以将仅 http 的网站和连结标注为...
直接看下去! 文件 文件原文:Physical Memory Model 翻译: ZONE_DEVI...
tensor简介: tensor是在pytorch运算时所使用的资料型态 就像numpy一样,可支持...