先写一个监听服务的文件,这里取名server.js(ws模块须要本身去安装, 命令是 npm i ws)css
const WebSocket = require('ws'); // 引入模块 const ws = new WebSocket.Server({port:3000},()=>{ // 监听接口 console.log("socket start") }) let clients = []; ws.on('connection',(client)=>{ //console.log("client:",client) clients.push(client) client.send("欢迎光临"); client.on('message',(msg)=>{ console.log("来自服务器的数据",msg); client.send(msg); // 经过send方法来给前端发送消息 //sendall(); }) client.on('close',(msg)=>{ console.log("关闭服务器链接") }) })
以后对这个这个文件 node启动,到对应文件目录下打命令 node server.js
html
命令框出现“socket start”字样就是说嘛服务启动了,以后就等待前台的命令了前端
html这里就作一个简单消息发送,而后把发送的消息回传回来node
<!DOCTYPE html> <html> <head> <title></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1></h1> <br> <input type="text" id="sendtext"><button onclick="send()">send</button> <script> const ws = new WebSocket("ws://localhost:3000/") // 监听地址端口号 ws.onopen = function(){ console.log("服务器链接") } ws.onmessage= (msg)=>{ console.log("来自服务器发来的数据"+msg.data) console.log("来自服务器msg",msg) alert("服务器返回内容:"+msg.data) } ws.onclose=()=>{ console.log("服务器关闭") } function send(){ //alert() let msg = document.getElementById("sendtext").value; //alert(msg) ws.send(msg) } </script> </body> </html>
这就完成了一个简单消息发送回传的功能,须要注意的是这里发送监听的端口须要和后端监听端口一致,这里写的是3000web
-- 这里只是用node和html实现一个简单的功能,可是基本原理都在这里了,能够根据本身的须要来搭建本身消息推送机制。npm