首先安装nodejs-websocket
npm install nodejs-websocket
构造如下程序:
wsServer.js
var ws = require("nodejs-websocket")
var PORT = 3000
var server = ws.createServer(function (conn) {
console.log("New connection")
conn.on("text", function (str) {
console.log("Received "+str)
conn.sendText(str.toUpperCase()+"!!!")
})
conn.on("close", function (code, reason) {
console.log("Connection closed")
})
conn.on("error", function(err){
console.log("handle err");
console.log(err);
})
}).listen(PORT)
前端代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<h1>Echo Test</h1>
<input id="sendTxt" type="text" />
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">
let websocket = new WebSocket("ws://127.0.0.1:3000");
websocket.onopen = function () {
console.log('websocket open');
document.getElementById("recv").innerText = "Connected";
}
websocket.onclose = function () {
console.log('websocket close');
}
websocket.onmessage = function (ev) {
console.log(ev.data);
document.getElementById("recv").innerHTML = ev.data;
}
document.getElementById("sendBtn").onclick = function () {
let txt = document.getElementById("sendTxt").value;
console.log(txt);
websocket.send(txt);
}
</script>
</body>
</html>
运行截图:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq78442761/article/details/121231555
内容来源于网络,如有侵权,请联系作者删除!