0%

websocket 一些小脚本

今天干活到 11 点半…….不知道写啥了………这个周接触 websocket 多些,就把用的几个小脚本分享一下,当完成任务了哈哈哈…….

websocket 测试页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
// var wsUri = "ws://localhost:8088"
var output;

function init() {
output = document.getElementById("output");
testWebSocket();
}

function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) {
onOpen(evt);
};
websocket.onclose = function (evt) {
onClose(evt);
};
websocket.onmessage = function (evt) {
onMessage(evt);
};
websocket.onerror = function (evt) {
onError(evt);
};
}

function onOpen(evt) {
writeToScreen("CONNECTED");
// doSend("WebSocket rocks");
}

function onClose(evt) {
writeToScreen("DISCONNECTED");
}

function onMessage(evt) {
writeToScreen(
'<span style="color: blue;">RESPONSE: ' + evt.data + "</span>"
);
websocket.close();
}

function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}

function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}

function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}

window.addEventListener("load", init, false);
</script>

<h2>WebSocket Test</h2>

<div id="output"></div>

python 版本的连接 websocket 并保存数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


import asyncio
import logging
from datetime import datetime

from aiowebsocket.converses import AioWebSocket



async def startup(uri):
async with AioWebSocket(uri) as aws:
converse = aws.manipulator
with open("./log.txt",'wb') as f:
while True:
await converse.send('90')
mes = await converse.receive()
# print(mes)
f.write(mes)
f.write('\n')

if __name__ == "__main__":
print("start")
remote = "ws://xxx.ws"
try:
asyncio.get_event_loop().run_until_complete(startup(remote))
except KeyboardInterrupt as exc:
logging.info("quit.")

与上面 python 脚本联动 ,模拟 websocket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const fs = require("fs");

//https://www.npmjs.com/package/ws
const WebSocket = require("ws");

try {
// read contents of the file
// How to read a file line by line in Node.js https://attacomsian.com/blog/reading-a-file-line-by-line-in-nodejs
const data = fs.readFileSync("log.txt", "UTF-8");

// split the contents by new line
const lines = data.split(/\r?\n/);

// print all lines
// lines.forEach(line => {
// const a = JSON.parse(line);
// console.log(line, typeof line, a.crossingName);
// });

let lineNum = 0;
const try3Times = () => {
let tryN = 0;

return function a() {
// console.log("debug:: 😈", "scratch.js::", "line No: 6: ", lineNum,)
lineNum = (lineNum + 1) % 100;
const d = lines[lineNum];
if (!d && tryN < 3) {
// console.log("debug:: 😈", "scratch.js::", "line No: 11: ",tryN ,d)

tryN += 1;
return a();
}
tryN = 0;
return d;
};
};

const fun = try3Times();
const Wss = new WebSocket.Server({ port: 8088 });

Wss.on("connection", (ws) => {
ws.on("message", function incoming(message) {
ws.send(fun());

console.log("received: %s", message);
});

console.log("connection");
ws.send(fun());
});
} catch (err) {
console.error(err);
}