服务端代码如下:
chart.js文件
const http = require('http');
const io = require('socket.io');
let httpServer = http.createServer(function(req, res){
console.log("http创建成功");
});
httpServer.listen(8080);
let wsServer = io.listen(httpServer);
let sockList = [];
wsServer.on('connection', sock=>{
sockList.push(sock);
console.log("连接成功");
sock.on('login_ret', (name, pass)=>{
sock.emit('login_ret', {code: '0', user: name, msg: "登录成功"});
});
sock.on('reg_ret', (name, pass)=>{
sock.emit('reg_ret', {code: '0', msg: "注册成功"});
});
// 消息通知
sock.on('message_ret', (text, user)=>{
sockList.forEach(function(item) {
item != sock && item.emit("message_ret", {
code: "0", user: user, msg: text
});
});
});
// 离线
sock.on('disconnect', ()=>{
sockList = sockList.filter(function(item){
return item != sock;
});
});
});
char.html
页面代码如下:
.chart_contain {
width: 100%;
height: 70%;
display: none;
}
.chart_content {
width: 100%;
height: 400px;
overflow: scroll;
}
.left {
float: left;
clear: both;
background-color: chartreuse;
}
.right {
float: right;
clear: both;
background-color: white;
}
.send_content {
width: 100%;
height: 100px;
}
var form = document.getElementsByTagName("form")[0];
var user = document.getElementById("userName");
var password = document.getElementById("password");
var regBtn = document.getElementById("regBtn");
var loginBtn = document.getElementById("loginBtn");
var content = document.getElementsByClassName("chart_contain")[0];
var sendBtn = document.getElementsByClassName("send_btn")[0];
var text = document.getElementsByClassName("send_content")[0];
var chart = document.getElementsByClassName("chart_content")[0];
var userName, password;
// 链接
var sock = io.connect("ws://localhost:8080/");
// 注册请求
regBtn.onclick = function() {
var name = user.value;
var pass = password.value;
sock.emit("reg_ret", name, pass);
};
// 登录请求
loginBtn.onclick = function() {
var name = user.value;
var pass = password.value;
sock.emit("login_ret", name, pass);
};
// 发送消息
sendBtn.onclick = function() {
sock.emit("message_ret", text.value, userName);
render(userName, userName, text.value);
text.value = "";
};
// 注册
sock.on("reg_ret", function(res) {
if(res.code == "0") {
alert("注册成功,请登录");
}
});
// 登录
sock.on("login_ret", function(res) {
if(res.code == "0") {
userName = res.user;
alert("登录成功");
content.style.display = "block";
form.style.display = "none";
}
});
// 发消息
sock.on("message_ret", function(res) {
if(res.code == "0") {
render(userName, res.user, res.msg);
}
});
function render(userName, sender, msg) {
var classTag = userName === sender ? "left" : "right";
var node = document.createElement("div");
node.innerHTML = `${sender}:
${msg}`;
node.className = classTag;
chart.appendChild(node);
}