nodejs-webSocket初次使用(页面链接和创建自己的服务)
总共两个文件(一个html和一个js):
页面代码(webSocket.html):
<html> <head> <title>WebSocketTest</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <style> #content{ width:50em; height:6em; overflow: hidden; overflow-y:scroll; color: red; border:2px solid #dedede; } </style> </head> <body> <input type="text" id='message' /> <input type="button" id='btn' value="Send" /> <div id='content'></div> </body> <script> //创建服务 var socket = new WebSocket("ws://localhost:9001/"); socket.addEventListener('open',function(){ $('#content').html('服务连接成功。'); }); $('#btn').click(function(){ var content = $('#message').val(); socket.send(content); }); socket.addEventListener('message',function(e){ console.log(e); $('#content').html(e.data); }); </script> </html>
服务(webSockerServer.js):
var ws = require("nodejs-websocket"); var server = ws.createServer(function(conn){ console.log("新链接"); conn.on("text",function(str){ console.log("接收到:" + str); conn.sendText(str + "(socket返回的数据:)"); }); conn.on("close",function(code,reson){ console.log("链接关闭!"); }); }).listen(9001);
安装文件:
软件:VSCode
1.首先,安装nodejs
2.在VSCode的【终端】上面使用命令【npm install nodejs-websocket】,安装nodejs-websocket(终端的快捷键:Ctrl+~,使用方法:https://www.npmjs.com/package/nodejs-websocket)
注:我这安装【nodejs-websocket】碰到两个问题
1)package.json文件不存在
2)本地继续安装nodejs-websocket异常(1问题后出现)
3.运行结果
感谢:
https://blog.csdn.net/weixin_40161974/article/details/99441501
https://blog.csdn.net/MyDilrabaSister/article/details/100668382
参考:
https://www.imooc.com/video/15319
https://www.bilibili.com/video/BV1yi4y1t7yD?p=3