<div id="room" class="panel panel-primary"> <div class="panel-heading clearfix"> 聊天室 <input id="nickname" placeholder="昵称,默认为新朋友" style="200px;" type="text" class="form-control pull-right"> </div> <div class="panel-body"> <div class="content"> <ul class="list-group msgs"></ul> </div> <div class="control-box"> <input id="word" type="text" class="form-control"> <button id="send" class="btn btn-success">发送</button> </div> </div> <div class="numbers"> <button class="btn btn-info online"> 在线人数:<span class="count"></span> </button> <ul class="list-group clients"> </ul> </div> </div> </body> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script> //创建客户端的连接socket // var wsc = new WebSocket('ws://127.0.0.1:2345'); var wsc = new WebSocket('ws://10.9.166.55:2345'); wsc.onopen = function (e) {//当客户端连接上的时候就会触发 //console.log('我已经连接上服务端了') }; wsc.onmessage = function (e) {//当服务端返回消息的时候触发 // console.log(e.data); let info = JSON.parse(e.data) switch(info.type){ case 'msg': handleMsg(info);break; case 'count': handleCount(info);break; } }; function handleMsg(info) { let str = ` <li class="list-group-item ${info.isMe?'me':'other'}"> <span>${info.nickname}</span> <button class="btn btn-success">${info.msg}</button> </li> ` let li = $(str) $(".msgs").append(li) li[0].scrollIntoView() } function handleCount(info) { $(".count").html(info.count) var str = '' info.clients.forEach(item => { str+='<li class="list-group-item list-group-item-info text-center">'+item+'</li>' }); $(".clients").html(str) //如果有人来或者有人走,需要报一个消息 if(info.nickname&&info._type){ $(".msgs").append('<p class="p-info text-center">'+info.nickname+(info._type==1?'加入聊天室':'离开聊天室')+'</p>') } } $("#send").click(function () { send() }) $("#word").keyup(function (e) { if(e.keyCode==13){ send() } }) function send() { var nickname = $("#nickname").val() || '新朋友' var msg = $("#word").val() wsc.send(JSON.stringify({nickname:nickname,msg:msg})) } var canUse = true wsc.onclose = function (e) {//当服务端关闭的时候触发 // alert('聊天服务已经关闭了') canUse = false }; wsc.onerror = function (e) {//错误情况触发 console.log(e) } </script>
服务端:
const http = require('http')
const fs = require('fs')
var server = http.createServer((req,res)=>{
res.writeHead(200,{'Content-Type':'text/html;charset=utf8'})
res.end(fs.readFileSync('./index.html'))
})
//socket
const Server = require('ws').Server
//建立好了服务端
var wss = new Server({server})
//存放前端连接的socket
var clientMap = {}
var count = 0
var id = 0
//当客户端连接上的就会触发,回调会接收一个socket对象
wss.on("connection",function (socket) {
count++
id++
socket.id = id
clientMap[socket.id] = socket
socket.nickname = '新朋友'
console.log(`现在有${count}人连接了`)
broadClients(socket.nickname,1)
//当这个客户端发送数据的时候会触发
socket.on("message",function (msg) {
//console.log(`客户端${socket.id} 说:${msg}`)
let info = JSON.parse(msg)
if(socket.nickname!=info.nickname){
socket.nickname = info.nickname
broadClients()
}
socket.nickname = info.nickname
broadcast(socket,info.msg)
})
//当客户端断开到时候触发
socket.on("close",function () {
//console.log(`客户端${socket.id} 说:${msg}`)
count--
let nickname = socket.nickname
delete clientMap[socket.id]
broadClients(nickname,2)
})
//当客户端连接出错的时候
socket.on("error",function (err) {
console.log(err)
})
})
//广播函数,像所有的客户端发送某一个客户端说的话
function broadcast(socket,msg) {
let info = {nickname:socket.nickname,msg:msg,type:'msg'}
for(var id in clientMap){
info.isMe = socket.id==id?'true':false
clientMap[id].send(JSON.stringify(info))
}
}
function broadClients(nickname,type) {
let clients = []
for(var id in clientMap){
clients.push(clientMap[id].nickname)
}
for(var id in clientMap){
clientMap[id].send(JSON.stringify({
count,clients,
type:'count',
nickname,_type:type
}))
}
}
server.listen(2345)
// server.listen(2345,'127.0.0.1')