WebSocket
//服务器代码 let WebSocket = require('ws'); // let server = new WebSocket.Server({port:3000}); let clients = []; //存入连入的客户端 server.on('connection',(client)=>{ client.id = clients.length; clients.push(client); //将连入的客户端存入到数组中 // client.setEncoding('utf8'); client.on('message',(data)=>{ for(let i = 0 ; i < clients.length ; i++){ if( clients[i] ){ //不能少s clients[i].send( data );//否则信息发不出去 } } }) // 退出登录 client.on('close',()=>{ clients[client.id] = null; }); // 出错 client.on('error',()=>{ clients[client.id] = null; }) })
//服务器代码 let http = require('http'); let urlStr = require('url'); let ejs = require('ejs'); let server = http.createServer((req,res)=>{ let pathname = urlStr.parse(req.url).pathname; if(pathname==='/'){ ejs.renderFile('./index.ejs',(err,html)=>{ res.end(html); }) } }).listen(4000,()=>{ console.log('start') })
<!--页面代码--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="text" id="txt"> <!-- <input type="file" id="txt" > --> <input type="button" id="btn" value='提交'> <div id="content"></div> </body> </html> <script> // let webScoket = new WebSocket('ws://127.0.0.1:3000'); let webScoket = new WebSocket('ws://10.9.157.60:8000'); let oIpt = document.getElementById('txt'); let oDiv = document.getElementById('content'); let oBtn = document.getElementById('btn'); oBtn.onclick =function(){ webScoket.send( oIpt.value ); } webScoket.onmessage = (message)=>{ oDiv.innerHTML += message.data + "<br>"; } </script>