${
data.msg}
不同的端口 登陆 属于不同的用户
先引入 socket.io插件
npm install --save socket.io
因为是基于express的,所以还需要install express;
npm install express --save
服务端代码(app.js)
//创建了http服务器
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/online-chat.html');
});
io.on('connection', function (socket) {
socket.emit('send', {
name: 'haha' });
});
客户端代码(inline-chat)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>在线聊天室title>
head>
<body>
body>
<script src="/socket.io/socket.io.js">script> //必须引入
<script>
var socket = io('http://localhost:3000'); //请求3000端口
socket.on('send', function (data) {
console.log(data);
});
script>
html>
// express使用静态资源
app.use(require('express').static('public'));
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>聊天室title>
<link rel="stylesheet" href="lib/jquery-mCustomScrollbar/css/jquery.mCustomScrollbar.min.css"/>
<link rel="stylesheet" href="lib/jquery-emoji/css/jquery.emoji.css"/>
<link rel="stylesheet" href="css/index.css" />
head>
<body>
<div class="login_box" style="display: block;">
<h3>用户登录h3>
<p>用户名p>
<input type="text" placeholder="请输入用户名" id="username" />
<p>选择头像p>
<ul class="avatar" id="login_avatar">
<li class="now"><img src="images/avatar01.jpg" alt="" />li>
<li><img src="images/avatar02.jpg" alt="" />li>
<li><img src="images/avatar03.jpg" alt="" />li>
<li><img src="images/avatar04.jpg" alt="" />li>
<li><img src="images/avatar05.jpg" alt="" />li>
<li><img src="images/avatar06.jpg" alt="" />li>
<li><img src="images/avatar07.jpg" alt="" />li>
<li><img src="images/avatar08.jpg" alt="" />li>
<li><img src="images/avatar09.jpg" alt="" />li>
<li><img src="images/avatar10.jpg" alt="" />li>
ul>
<button class="weui-btn" id="loginBtn">登录button>
div>
<div class="container" style="display: none;">
<div class="user-list">
<div class="header">
<div class="avatar">
<img class="img avatar_url" src="images/avatar2.jpg" alt="" />
div>
<div class="info">
<h3 class="username">清流h3>
div>
div>
<div class="title"><h3>用户列表h3>div>
<ul>
ul>
div>
<div class="box">
<div class="box-hd"><h3>聊天室(<span id="userCount">99span>)h3>div>
<div class="box-bd">
div>
<div class="box-ft">
<div class="toolbar">
<a href="javascript:;" title="表情" class="face">a>
<a href="javascript:;" title="截屏" class="screen-cut">
a>
<a href="javascript:;" title="图片" class="file">
<label for="file">label>
<input type="file" id="file" style="display: none;">
a>
div>
<div class="content">
<div class="text" id="content" contenteditable>div>
div>
<div class="action">
<span class="desc">按下Ctrl+Enter发送span>
<a class="btn-send" id="btn-send" href="javascript:;">发送a>
div>
div>
div>
div>
div>
<script src="/socket.io/socket.io.js">script>
<script src="js/jquery-1.12.4.js">script>
<script src="lib/jquery-mCustomScrollbar/script/jquery.mCustomScrollbar.min.js">script>
<script src="lib/jquery-emoji/js/jquery.emoji.min.js">script>
<script src="js/index.js">script>
body>
html>
* {
margin: 0;
padding: 0;
list-style: none;
}
html,
body {
height: 100%;
}
body {
background: url('../images/bg.jpg') no-repeat center center;
background-size: cover;
}
.container {
max-width: 1000px;
min-width: 800px;
height: 100%;
margin: 0 auto;
background-color: pink;
}
.user-list {
width: 280px;
height: 100%;
float: left;
position: relative;
background-color: #2e3238;
}
.box {
overflow: hidden;
height: 100%;
background-color: #eee;
position: relative;
}
.box-hd {
text-align: center;
position: absolute;
top: 0;
left: 0;
width: 100%;
line-height: 30px;
}
.box-hd h3 {
font-size: 18px;
font-weight: 400;
padding: 10px 0;
margin: 0 20px;
border-bottom: 1px solid #ccc;
z-index: 999;
box-sizing: border-box;
}
.message-box {
overflow: hidden;
}
.box-bd {
position: absolute;
width: 100%;
bottom: 180px;
top: 51px;
overflow-y: auto;
overflow-x: hidden;
}
.system {
overflow: hidden;
}
.message_system {
text-align: center;
margin: 10px auto;
max-width: 50%;
}
.message_system .content {
display: inline-block;
font-size: 12px;
padding: 1px 18px;
color: #b2b2b2;
border-radius: 2px;
}
.other {
margin-bottom: 16px;
float: left;
width: 100%;
padding-left: 20px;
box-sizing: border-box;
}
.my {
margin-bottom: 16px;
float: right;
width: 100%;
text-align: right;
padding-right: 20px;
box-sizing: border-box;
}
.my.message .avatar {
float: right;
}
.message .content {
overflow: hidden;
}
.message .content .nickname {
font-weight: 400;
padding-left: 10px;
font-size: 12px;
height: 22px;
line-height: 24px;
color: #4f4f4f;
width: 350px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
word-wrap: normal;
}
.message .avatar {
width: 40px;
height: 40px;
border-radius: 2px;
float: left;
cursor: pointer;
}
.my.message .bubble {
background-color: #b2e281;
}
.message .bubble {
max-width: 500px;
min-height: 1em;
display: inline-block;
vertical-align: top;
position: relative;
text-align: left;
font-size: 14px;
border-radius: 3px;
margin: 0 10px;
background-color: #fff;
}
.message .bubble img {
display: inline-block;
cursor: pointer;
max-width: 350px;
max-height: 240px;
}
.other .bubble:before {
position: absolute;
top: 14px;
left: -10px;
border: 6px solid transparent;
content: ' ';
border-right-color: #fff;
border-right-width: 4px;
}
.my .bubble:before {
position: absolute;
top: 14px;
right: -10px;
border: 6px solid transparent;
content: ' ';
border-left-color: #b2e281;
border-left-width: 4px;
}
.bubble_cont {
word-wrap: break-word;
word-break: break-all;
min-height: 25px;
padding: 9px 13px;
}
.box-ft {
border-top: 1px solid #ccc;
position: absolute;
height: 180px;
bottom: 0;
right: 0;
left: 0;
}
.box-ft .toolbar {
height: 30px;
padding: 5px 20px;
}
.box-ft .toolbar .face {
display: inline-block;
vertical-align: middle;
width: 30px;
height: 30px;
background: url('../images/wechat-sprit.png') no-repeat -404px -398px;
}
.box-ft .toolbar .screen-cut {
display: inline-block;
vertical-align: middle;
width: 30px;
height: 30px;
background: url('../images/wechat-sprit.png') no-repeat -30px -432px;
}
.box-ft .toolbar .file label {
opacity: 0;
width: 100%;
height: 100%;
display: block;
cursor: pointer;
background: rgb(255, 255, 255);
}
.box-ft .toolbar .file {
display: inline-block;
vertical-align: middle;
width: 30px;
height: 30px;
background: url('../images/wechat-sprit.png') no-repeat -120px -432px;
}
.box-ft .content {
height: 90px;
overflow-x: hidden;
padding: 0px 20px;
}
.box-ft .content .text {
resize: none;
border: none;
outline: none;
width: 100%;
height: 84px;
font-size: 16px;
background-color: #eee;
}
.box-ft .action {
text-align: right;
margin-top: 5px;
padding-right: 20px;
}
.box-ft .action .desc {
color: #888;
font-size: 12px;
margin-left: 10px;
margin-right: 7px;
}
.btn-send {
display: inline-block;
border: 1px solid #c1c1c1;
text-decoration: none;
background-color: #fff;
color: #222;
border-radius: 4px;
padding: 3px 30px;
font-size: 14px;
}
.btn-send:hover {
background-color: #d8d8d8;
}
.header {
padding: 18px;
position: relative;
}
.header .avatar {
display: table-cell;
vertical-align: middle;
word-wrap: break-word;
word-break: break-all;
white-space: nowrap;
padding-right: 10.625px;
}
.header .avatar .img {
width: 40px;
height: 40px;
border-radius: 2px;
display: block;
cursor: pointer;
}
.header .info {
display: table-cell;
vertical-align: middle;
word-wrap: break-word;
word-break: break-all;
width: 2000px;
}
.header .info h3 {
display: inline-block;
font-weight: 400;
width: 156px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
word-wrap: normal;
color: #fff;
font-size: 18px;
vertical-align: top;
line-height: 31px;
text-decoration: none;
}
.title {
padding: 13px 18px 11px;
border-bottom: 1px solid #24272c;
border-top: 1px solid #24272c;
color: #fff;
}
.title h3 {
font-weight: 400;
font-size: 18px;
}
.user {
overflow: hidden;
padding: 12px 18px 11px;
border-bottom: 1px solid #292c33;
cursor: pointer;
position: relative;
}
.user .avatar {
float: left;
margin-right: 10px;
position: relative;
}
.user .avatar img {
display: block;
width: 40px;
height: 40px;
border-radius: 2px;
}
.user .name {
color: #fff;
overflow: hidden;
line-height: 36px;
}
.login_box {
position: absolute;
top: 50%;
left: 50%;
width: 380px;
height: 380px;
transform: translate(-50%, -50%);
border-radius: 4px;
background-color: #fff;
box-shadow: #999 0 2px 10px;
}
.login_box h3 {
text-align: center;
color: #333;
font-size: 24px;
font-weight: 400;
line-height: 100px;
}
.login_box input {
width: 300px;
height: 30px;
line-height: 30px;
margin: 0 auto;
padding: 0;
display: block;
outline: none;
margin-bottom: 5px;
}
.weui-btn {
position: relative;
display: block;
width: 300px;
margin: 0 auto;
box-sizing: border-box;
font-size: 14px;
text-align: center;
text-decoration: none;
color: #ffffff;
line-height: 2.55555556;
border-radius: 5px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
overflow: hidden;
background-color: #1aad19;
border: none;
cursor: pointer;
margin-top: 5px;
}
.login_box ul {
overflow: hidden;
width: 280px;
margin: 0 auto;
border: 1px solid #ccc;
padding: 0 10px;
}
.login_box li {
float: left;
width: 44px;
height: 44px;
border: 2px solid transparent;
margin: 0 4px;
cursor: pointer;
}
.login_box li.now {
border-color: #1aad19;
}
.login_box img {
width: 40px;
height: 40px;
display: block;
}
.login_box p {
height: 30px;
line-height: 30px;
padding-left: 38px;
}
::-webkit-scrollbar-track-piece {
background-color: #f8f8f8;
}
::-webkit-scrollbar {
width: 6px;
height: 6px;
border-radius: 3px;
}
::-webkit-scrollbar-thumb {
background-color: #ccc;
background-clip: padding-box;
min-height: 28px;
}
::-webkit-scrollbar-thumb:hover {
background-color: #666;
}
index.js
/*
1. 连接socketio服务
*/
var socket = io('http://localhost:3000')
var username, avatar
/*
2. 登录功能
*/
$('#login_avatar li').on('click', function() {
$(this)
.addClass('now')
.siblings()
.removeClass('now')
})
// 点击按钮,登录
$('#loginBtn').on('click', function() {
// 获取用户名
var username = $('#username')
.val()
.trim()
if (!username) {
alert('请输入用户名')
return
}
// 获取选择的头像
var avatar = $('#login_avatar li.now img').attr('src')
// 需要告诉socket io服务,登录
socket.emit('login', {
username: username,
avatar: avatar
})
})
// 监听登录失败的请求
socket.on('loginError', data => {
alert('用户名已经存在')
})
// 监听登录成功的请求
socket.on('loginSuccess', data => {
// 需要显示聊天窗口
// 隐藏登录窗口
$('.login_box').fadeOut()
$('.container').fadeIn()
// 设置个人信息
console.log(data)
$('.avatar_url').attr('src', data.avatar)
$('.user-list .username').text(data.username)
username = data.username
avatar = data.avatar
})
let users=[];//记录所有已经登陆的用户
io.on('connection', function (socket) {
socket.on("login",data=>{
// 判断该账号是否已经被登陆
let user = users.find(item =>item.username===data.username);
if(user){
//该账户已经存在,登陆失败
socket.emit('login',{
msg:"登录失败"})
console.log("登陆失败");
}else{
//该用户不存在,登陆成功
users.push(data);
socket.emit('loginSuccess',data) //这两个data不可以携程user,因为user是空的
console.log("登陆成功");
}
})
});
在这里插入代码片
//广播告诉所有人 有人进来了
io.emit("addUser",data);
// 监听添加用户的消息
socket.on('addUser', data => {
// 添加一条系统消息
$('.box-bd').append(`
`
)
scrollIntoView();//该方法用于使聊天记录可以上下移动(这样就不会只能看到一页的聊天记录)
})
//把所有用户列表重新渲染出来
io.emit("userList",users);
// 监听用户列表的消息
socket.on('userList', data => {
// 把userList中的数据动态渲染到左侧菜单
$('.user-list ul').html('')
data.forEach(item => {
$('.user-list ul').append(`
${
item.avatar}" alt="" />
${
item.username}
`)
})
$('#userCount').text(data.length)
})
//把用户信息存到socket中,方便退出时,告诉大家(这一步时在登录时做的)
socket.username=data.username;
socket.avatar=data.avatar;
**
到这里需要解释下说明socket 和 io 的区别,io 是广播给所有用户的,而socket 是属于该登录的用户自己拥有的
当socket.emit()的时候也是把信息只发送给该用户
所以你会发现在客户端,接受的方式都是socket.on();
//当用户退出聊天室时
socket.on('disconnect',function () {
console.log("关闭");
let index = users.findIndex(item=>item.username===socket.username);
users.splice(index,1);
//告诉大家有人退出了聊天室
io.emit("delUser",{
username:socket.username,
avatar:socket.avatar
})
//重新渲染用户列表
io.emit("userList",users);
})
// 监听用户离开的消息
socket.on('delUser', data => {
// 添加一条系统消息
$('.box-bd').append(`
`
)
scrollIntoView()
})
//接受用户发送的信息
socket.on("sendMessage",data=>{
//把消息广播给所有人
io.emit("receiveMessage",data)
})
// 聊天功能
$('.btn-send').on('click', () => {
// 获取到聊天的内容
var content = $('#content').html()
$('#content').html('')
if (!content) return alert('请输入内容')
// 发送给服务器
socket.emit('sendMessage', {
msg: content,
username: username,
avatar: avatar
})
})
// 监听聊天的消息
socket.on('receiveMessage', data => {
// 把接收到的消息显示到聊天窗口中
if (data.username === username) {
// 自己的消息
$('.box-bd').append(`
`)
} else {
// 别人的消息
$('.box-bd').append(`
`)
}
scrollIntoView()
})
//接受用户发送的图片
socket.on("sendImage",data=>{
//把图片广播给所有人
io.emit("receiveImage",data)
})
在这里插入代码片
// 发送图片功能
$('#file').on('change', function() {
var file = this.files[0]
// 需要把这个文件发送到服务器, 借助于H5新增的fileReader
var fr = new FileReader()
fr.readAsDataURL(file)
fr.onload = function() {
socket.emit('sendImage', {
username: username,
avatar: avatar,
img: fr.result
})
}
})
// 监听图片聊天信息
socket.on('receiveImage', data => {
// 把接收到的消息显示到聊天窗口中
if (data.username === username) {
// 自己的消息
$('.box-bd').append(`
`)
} else {
// 别人的消息
$('.box-bd').append(`
`)
}
// 等待图片加载完成,在滚动到底部
$('.box-bd img:last').on('load', function() {
scrollIntoView()
})
})
jquery-emoji文档
首先在页面上引用css文件和js文件,css文件一般在中添加,js文件一般在之前添加。注意要先引用jquery和jquery.mCustomScrollbar,再引用该js。
<link rel="stylesheet" href="lib/jquery-mCustomScrollbar/css/jquery.mCustomScrollbar.min.css"/>
<link rel="stylesheet" href="lib/jquery-emoji/css/jquery.emoji.css"/>
<link rel="stylesheet" href="css/index.css" />
<script src="/socket.io/socket.io.js"></script>
<script src="js/jquery-1.12.4.js"></script>
<script src="lib/jquery-mCustomScrollbar/script/jquery.mCustomScrollbar.min.js"></script>
<script src="lib/jquery-emoji/js/jquery.emoji.min.js"></script>
<script src="js/index.js"></script>
/ 初始化jquery-emoji插件
$('.face').on('click', function() {
$('#content').emoji({
// 设置触发表情的按钮
button: '.face',
showTab: false,
animation: 'slide',
position: 'topRight',
icons: [
{
name: 'QQ表情',
path: 'lib/jquery-emoji/img/qq/',
maxNum: 91,
excludeNums: [41, 45, 54],
file: '.gif'
}
]
})
})
**
**
点击获取源码