最近新get了一招,先上图:
看到这是不是很熟悉呢,有没有一种想拿鼠标拖一拖的错觉呢。没错它就是模仿了qq群聊的样式,不过功能暂时不多只能发文字。这个在线聊天室使用了web-socket协议的功能并以node.js为后台进行编写,具体实现的机制是:
每个用户向进入界面后将与服务器连接,连接成功后用户向服务器发送的消息将被广播到所有正在连接该服务器的用户(即把该消息发送到连接到服务器的所有用户,因此实现了群聊的功能)
①用户将通过 var socket = io.connect("/") 发起与服务器的连接,服务器通过io.on("connection",function(socket){}响应。
②前端通过socket.send()进行发送,后台通过socket.on('message',function(msg)) 接收,io.mit('message',msg)广播。
后台代码:
const http = require("http");
const fs = require('fs');
const ws = require("socket.io");
let friends = [];
const server = http.createServer(function(req,res){
// 读取文件,发送到前端
const html = fs.readFileSync('./www/index.html');
res.write(html);
});
// 基于当前web服务开启socket实例
const io=ws(server);
// 检测连接事件
io.on("connection",function(socket){
console.log('连接');
// 接收客户端发送的消息,并广播出去
socket.on("message",function(mes){
console.log(mes);
// 向所有的客户端广播消息
if(mes.msg==undefined){
if(mes.out) {
// io.emit("message",mes);
friends.splice(friends.indexOf(mes.out),1);
io.emit("message",{"friends":friends,"out":mes.out});
}else {
friends.push(mes);
console.log("friends"+friends);
io.emit("message",{"friends":friends,"add":mes});
}
}else {
// console.log(mes);
io.emit("message",mes);
}
});
})
server.listen(8080);
node刚学,可能写的很丑,忘留下宝贵建议。
前端(html)
<body>
<p id="agin">刷新重来</p>
<div id="container">
<div id="head">
进来的都是真爱,发给好友试试吧
</div>
<div id="record-box">
<div id="addInfo">
qpq加入聊天室
</div>
</div>
<div id="friends-box">
<p>群成员 <span>10</span></p>
<ul id="friend-list">
<!-- <li><em></em><span>sjkcnb</span></li> -->
</ul>
</div>
<div id="send-box">
<div class="function">
表情功能,尽情期待……
<div class="look">
<!-- <img src="img/Smile.png" alt="smile" width="100%"> -->