socket
user/index.js
const UserList=[]
const join=(socketId,userInfo)=>{
const oUser= Object.assign({socketId},userInfo)
UserList.push(oUser)
}
const remove=(socketId)=>{
var idx=UserList.findIndex(item=>item.socketId==socketId)
UserList.splice(idx,1)
}
const find=(socketId)=>{
return UserList.find(item=>item.socketId==socketId)
}
const findAll=()=>{
return UserList
}
module.exports={
join,
find,
findAll,
remove,
}
app.js
const user=require("./user")
const express=require("express")
const app=express()
const server=require("http").createServer(app)
const io=require("socket.io")(server,{
// cors:true
})
//配置静态资源
app.use(express.static("./public"))
//接收连接
io.on("connection",(socket)=>{
//1.得到 socketId
let socketId=socket.id
//2.得到昵称
let nickname=socket.handshake.query.nickname
console.log("欢迎:"+nickname);
user.join(socketId,{nickname})
//3.告诉浏览器,现在在线的人数
io.emit("online",user.findAll())
//4.绑定断开连接事件
socket.on("disconnect",function(){
user.remove(socketId)
io.emit("online",user.findAll())
})
//5.接收前端发送过来的数据
socket.on("to-server",function(data){
let {msg,receiveId}=data
//判断 receiveId是否有值
//如果没有值,就是发送给所有的人(广播)
//有值就发送给指定的人
if (receiveId==undefined || receiveId=="") {
socket.broadcast.emit("to-client",{msg,nickname})
}else{
socket.to(receiveId).emit("to-client",{msg,nickname})
}
})
})
server.listen(8080,()=>{
console.log("服务器启动完毕!");
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./js/jquery.js"></script>
<script src="./js/layer/layer.js"></script>
<script src="./js/socket.io.js"></script>
</head>
<body>
<style>
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 800px;
width: 800px;
border: 1px solid #000;
}
.container .top {
height: 600px;
border: 1px solid #000;
display: flex
}
.container .top .left {
flex: 1;
border: 1px solid #000;
overflow-y: scroll;
}
.container .top .left ul,
.container .top .left li {
list-style: none;
margin: 0;
padding: 0;
}
.container .top .right {
width: 100px;
border: 1px solid #000;
}
.container .top .msg {
height: 25px;
line-height: 25px;
margin-top: 2px !important;
/* border: 1px solid #000; */
/* display: inline-flex */
}
.container .top .msg div {
background-color: greenyellow;
display: inline-block;
border-radius: 10px;
padding-left: 5px;
padding-right: 5px;
}
.container .top .me {
text-align: right;
}
.container .top .me div {
background-color: pink;
}
ul,
li {
list-style: none;
margin: 0;
padding: 0px;
}
</style>
<div class="container">
<div class="current">当前用户:<span class="user">xxxx</span>
<span class="count" style="float:right">当前在线人数:<label style="color:red">0</label> </span>
</div>
<div class="top">
<div class="left">
<ul id="msgList">
<li class="msg">
<div>张三说: <span>xxxx</span> </div>
</li>
<li class="msg me">
<div><span>xxxx</span>:我</div>
</li>
</ul>
</div>
<div class="right">
<select multiple style="width: 100%;height:100%">
<option value="">所有人</option>
<option value="">张三</option>
<option value="">张三</option>
</select>
</div>
</div>
<div class="buttom">
<textarea style="width: 90%" cols="30" rows="10"></textarea>
<button class="send">发送</button>
</div>
</div>
</body>
</html>
<script>
layer.prompt({
formType: 2,
value: '王富贵' + parseInt(Math.random() * 1000),
title: '请输入用户名',
// area: ['800px', '350px'] //自定义文本域宽高
}, function (value, index, elem) {
$(".user").text(value);
$(".user").attr("userid", value);
$(".user").attr("uid", parseInt(Math.random() * 100000));
layer.close(index);
//连接服务器
connection(value)
});
function connection(username){
const socket=io("http://127.0.0.1:8080?nickname="+username)
//----------------------------------
//监听上线的事件
socket.on("online",function(data){
//这个data是个数组 有[{socketId},nickname]
console.log(data);
let strHtml=` <option value="">所有人</option> `
data.forEach(item=>{
strHtml+=`
<option value="" sid=${item.socketId}>${item.nickname}</option>
`
})
$("select").html(strHtml)
//2.显示在线人数
$(".count label").text(data.length)
})
//---------------------------------
//绑定点击事件
$(".send").on("click",function(){
let msg=$("textarea").val() //得到输入的内容
let receiveId=$("select option:selected").attr("sid")
socket.emit("to-server",{receiveId,msg})
//清空输入的内容
$("textarea").val("")
$("#msgList").append(`
<li class="msg me">
<div><span>${msg}</span>:我</div>
</li>
`)
})
//--------------------------------
//接收服务器的数据
socket.on("to-client",function(data){
const {msg,nickname}=data
$("#msgList").append(`
<li class="msg">
<div>${nickname}说: <span>${msg}</span> </div>
</li>
`)
})
}
</script>