基于H5的webSocket( 应用于移动端 )
***为自定义内容
/*
页面客户端index.html
1. 引入wsClient.js
2. 写事件驱动发送数据
ws.send(val)
给服务器发送数据
*/
/*
客户端连接服务器文件wsClient.js
h5 提供了一个 Socket 的全局对象
*/
const ws = new WebSocket( 'ws://***.***.***.***:****' )
ws.onopen = () => {
ws.send( '欢迎来到xxx的直播间' )
}
ws.onmessage = ( msg ) => {
const content = document.querySelector( '#content' );//获取页面input内容
content.innerHTML += msg.data + '<br/>'//输出页面内容
}
ws.onerror = ( error ) => {
if( error ){
console.log( error )
}
}
ws.onclose = () => {
console.log( `xxx下线了` )
}
/*
这个静态服务器是为了展示客户端界面的app.js
*/
const express = require( './node_modules/express' );
const app = express();
const port = ***;
const hostname = '***.***.***.***';
const path = require( 'path' );
// 需要设置一个静态文件夹 让我们的服务器找到client/index.html
app.use( express.static( path.join( __dirname,'client' )) )
app.listen( port,hostname,() => {
console.log( `The web Server is running at: http://${ hostname }:${ port }` )
})
/*
主服务器server.js
1. 通过ws模块来创建服务器
2. 服务器连接客户端
- 给客户端编号
3. 接收客户端发来的信息
4. 监听客户端下线
*/
// 1. 通过 ws模块 来创建服务器
const webSocket = require( './node_modules/ws' );
const ws = new webSocket.Server({
port: ***,
host: '***.***.***.***'
})
// 2. 服务器连接客户端
const clients = {};
let count = 0;
ws.on( 'connection', client => {
//给客户端编号
client.name = ++count;
clients[ client.name ] = client
//接收客户端发来的数据
client.on( 'message', msg => {
console.log( `客户端 ${ client.name }说:${ msg }`)
boardcast( client,msg )
})
//监听客户端下线
client.on( 'close', () => {
delete clients[ client.name ]
console.log( `客户端 ${ client.name } closed~~` )
})
})
//广播
function boardcast ( client,msg ) {
for( var key in clients ){
clients[ key ].send( msg )
}
}