socket.io实现简单多人聊天室

设计理念

相当于一个微信群聊,登录进入群聊,实现多人聊天。

效果图

在这里插入图片描述

1 初始化项目

前提是已经安装并且能够熟练使用nodejs
打开终端或者cmd 进入你的项目根目录

npm init -y

初始化项目,直到生成以下文件,才算成功。
在这里插入图片描述

2下载需要使用的包到依赖上

npm i express nodemon socket.io --save

根目录有node_modules ,以及package.json下有以下内容。

在这里插入图片描述

3搭建服务器

服务器的名称必须和package.json中的mian下边的文件名一样。
在这里插入图片描述

4服务器搭建成功

在这里插入图片描述

5配置公共文件夹

  1. 根目录下新建文件夹public

在这里插入图片描述

  1. main.js文件下边输入以下代码
app.use(express.static('public'));
  1. 重启服务器,浏览器打开localhost:3000,默认打开public下边的index.html文件。

  2. 点击socket.io.js下载解压找到dist/socket.io.js文件,写入public文件中,导入index.html

多人聊天室代码

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>聊天室</title>
    <script src="js/socket.io.min.js"></script>
    <link rel="stylesheet" href="css/index.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script src="js/chat.js"></script>
</head>

<body>
    <div class="login-wrap">
        <div class="login-con">
            <h3>用户登录</h3>
            <input type="text" placeholder="请输入昵称" id="loginName" />
            <button class="login-btn">登录</button>
        </div>
    </div>
    <div class="chat-wrap hide">
        <h1>多人聊天室</h1>
        <div class="chat-con clearfix"></div>
        <div class="bottom">
            <input type="text" id="sendtxt" />
            <button class="sendBtn">发送</button>
        </div>
    </div>

</body>

</html>

css

/*公共样式*/

* {
    padding: 0;
    margin: 0;
}

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden
}

.clearfix {
    *zoom: 1
}

.cred {
    color: #f03e3e;
}

.cgreen {
    color: #459d36;
}

.hide {
    display: none;
}

.fr {
    float: right;
}

.fl {
    float: left;
}

.rela {
    position: relative;
}

.abs {
    position: absolute;
}

h1 {
    margin: 0 auto;
    z-index: 20;
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-size: 20px;
    background: #000;
    color: #fff;
    text-align: center;
}

.login-wrap,
.chat-wrap {
    background-color: #f1d4d4;
    width: 600px;
    height: 800px;
    margin: 0 auto;
    text-align: center;
    position: relative;
}

.chat-con {
    height: 697px;
    overflow-y: scroll;
}

.login-con {
    padding-top: 50px;
}

.login-con h3 {
    margin-bottom: 20px;
}

.login-con input,
.login-con button {
    width: 400px;
    display: block;
    margin: 0 auto;
    height: 40px;
    line-height: 40px;
    margin-top: 40px;
}

.login-con button {
    background: #FFA07A;
    border: none;
    cursor: pointer;
    outline: 1px solid #ececee;
}

.bottom {
    position: absolute;
    width: 600px;
    height: 50px;
    bottom: 0px;
    left: 0;
    line-height: 50px;
}

.bottom input {
    width: 540px;
    height: 50px;
    float: left;
    outline: none;
    border: 1px solid black;
}

.bottom .sendBtn {
    width: 50px;
    height: 50px;
    line-height: 50px;
    float: left;
    outline: none;
}

.chat-item {
    width: 100%;
    margin-bottom: 20px;
}

.item-right .message {
    background: #62b900;
}

.item-left .message {
    background: #fff;
    margin-top: 20px;
}

.item-left .img {
    margin-right: 10px;
}

.item-left .uname {
    font-size: 12px;
    left: 50px;
    top: 0;
}

.chat-item .message {
    width: 60%;
    display: block;
    padding: 10px;
    border-radius: 5px;
    margin-right: 10px;
}

.chat-item .img {
    display: inline-block;
    width: 40px;
    height: 40px;
    background: url(../img/1.jpg) no-repeat;
    background-size: 100% 100%;
}

.item-right .img {
    background: url(../img/2.jpg) no-repeat;
    background-size: 100% 100%;
}

.item-right .uname {
    font-size: 12px;
    right: 50px;
    top: 0;
}

js

$(function() {
    var socket = io();
    var uname = null;
    $('.login-btn').click(function() {
        uname = $('#loginName').val();
        // 2通过login用户名传递给服务器------------------
        if (uname) {
            socket.emit('login', {
                username: uname
            });
        } else {
            alert('清输入昵称')
        }
        // 6失败提示昵称重复---------------------
        socket.on('loginFail', (data) => {
                alert('昵称重复');
            })
            // 7登录成功后显示加入群聊----------------------------
            // 8点击发送把value的值传入服务器---------------------

    })
    socket.on('leave', (data) => {
            if (data != null) {
                let p = `<p>${data}已退出群聊</p>`;
                $('.chat-con').append(p);
            }
        })
        // 6登录成功跳转到聊天室{username: "xsxs cdscd"}--------------------
    socket.on('loginSuccess', (data) => {
        if (data.username == uname) {
            checkiIn(data);
            socket.on('add', (data) => {
                console.log(data);
                let p = `<p>${data.username}已加入群聊</p>`;
                $('.chat-con').append(p);
            })
        } else {
            alert('用户名不匹配')
        }
    })
    $('.sendBtn').click(function() {
            sendMsg();
        })
        // 10接受服务器的所有写入信息,写入页面-----------------------
    socket.on('receiveMessage', (data) => {
        showMessage(data)
        console.log(data);
    });
    $(document).keydown(function() {
        if (event.keyCode == 13) {
            sendMsg();
        }
    })

    function sendMsg() {
        var text = $('#sendtxt').val();
        $('#sendtxt').val('');
        if (text) {
            socket.emit('sendMseeage', {
                username: uname,
                message: text
            })
        }
    }

    function showMessage(data) {
        // { username: 'xs ', message: '从v的师傅荟萃' }
        console.log(data);
        var p = null;
        if (data.username == uname) {
            p = ` <div class="chat-item item-right clearfix">
                <span class="img fr"></span> 
                <span class="message fr">${data.message }</span>
                 </div>`
        } else {
            p = `<div class="chat-item item-left clearfix rela"><span class="abs uname"> ${data.username}</span><span class="img fl"></span><span class="fl message"> ${data.message }</span></div>`
        }
        $('.chat-con').append(p);
    }
})

function checkiIn(data) {
    $('.login-wrap').hide();
    $('.chat-wrap ').show();
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值