简易WebScoket学习(使用WS模块)
实现功能:客户端与服务器建立socket后,服务器接收到客户端消息后返回给除自己外的其他客户端信息
1.需提前安装express
npm install express -a
2.服务端
var app = require('express')()
var server = require('http').Server(app)
var WebSocket = require('ws')
var wss = new WebSocket.Server({ port: 8080 })//
let arr =[] //建立数组存储所有接入client的信息
wss.on('connection', function connection(ws) {
console.log('server: receive connection.'+ws._ultron.id)
ws.on('message', function incoming(message) { //接收到消息
// console.log('client:'+ws._ultron.id+"send Info", message)//
ws._ultron.id 相当于clientID
arr.push({client:ws._ultron.id,msg:message})
wss.clients.forEach(function(item){ //广播
if(item._ultron.id==ws._ultron.id){return}
// console.log(item._ultron)
item.send(JSON.stringify(arr))
})
})
ws.on('pong', () => {
console.log('server: received pong from client');
})//ws是通过ping/pong 心跳维护连接的
//ws.send('world');
// setInterval(() => {
// ws.ping('', false, true);
// }, 2000);
})
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
})
app.listen(3000)
3.web端
sendToServer
var ws = new WebSocket('ws://localhost:8080')
ws.onopen = function () {
document.getElementById("bt1").onclick=function(e){
let info = document.getElementById("input1").value
ws.send(info)
}
console.log('client: ws connection is open')
ws.send('hello') }
ws.onmessage = function (e) {
console.log( e.data) }