Node.js笔记-使用nodejs-websocket构建WebSocket服务
生活随笔
收集整理的這篇文章主要介紹了
Node.js笔记-使用nodejs-websocket构建WebSocket服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先安裝nodejs-websocket
npm install nodejs-websocket構造如下程序:
wsServer.js
var ws = require("nodejs-websocket")var PORT = 3000var 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>運行截圖:
總結
以上是生活随笔為你收集整理的Node.js笔记-使用nodejs-websocket构建WebSocket服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nginx笔记-反向代理中配置WebSo
- 下一篇: MySQL笔记-Linux平台中MySQ