Node.js用Socket.IO做聊天软件的实现示例

lxf2023-11-16 15:50:01
摘要

本文主要介绍了Node.js用Socket.IO做聊天软件的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

目录
  • 效果
  • index.html文件
  • index.js
  • 实现方法

效果

Node.js用Socket.IO做聊天软件的实现示例

index.html文件

页面主要是渲染聊天界面

<!DOCTYPE html>
<html>
<head>
    <title>Socket.io chat</title>
    <style>
        body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "SeGoe UI", Roboto, Helvetica, Arial, sans-serif; }

        #fORM { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
        #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
        #input:focus { outline: none; }
        #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages > li { padding: 0.5rem 1rem; }
        #messages > li:nth-child(odd) { background: #efefef; }
        .message{font-size: 40px;color: skyblue}
        .name{font-size: 15px;color: pink}
    </style>
</head>
<body>
<ul ></ul>
<form  action="">
    <input  autocomplete="off" name="main" /><button>Send</button>
</form>
<script ></script>
<script>
    let name=prompt("输入用户名");
    //拿到用户名后进行非空验证
    if(name == '' || name == null){
        alert("先输入用户名")
    }else {
    	//初始化socket模块
        var socket = io();
        socket.emit('name message',name);//向服务器发送消息(用户名信息)
        let form = document.getElementById('form');
        let inputMain = document.querySelector('input[name="main"]');
        form.addEventListener('submit', function(e) {
            e.preventDefault();//取消默认提交事件
            if (inputMain.value) {//如果文本框中有消息
                socket.emit('chat message', inputMain.value);//向服务器发送消息(聊天信息)
                inputMain.value = '';
            }

        });
        //渲染服务器端发送的用户名信息(不仅是自己的,还有别的用户的)
        socket.on('name message',function (msg){
            var item = document.createElement('li');
            item.classList.add("name")
            item.textContent = msg;
            messages.appendChild(item);
        })
        //渲染服务器端发送的聊天信息(不仅是自己的,还有别的用户的)
        socket.on('chat message', function(msg) {
            var item = document.createElement('li');
            item.classList.add("message")
            item.textContent = msg;
            messages.appendChild(item);
            window.scrollTo(0, document.body.scrollHeight);
        });
    }
</script>
</body>
</html>

index.js

该文件主要用于聊天信息后端处理

const express = require('express');
const app = express();
const Http = require('http');
const server = http.createServer(app);
//引入socket.io
const {Server}=require('socket.io')
const io=new Server(server)

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
io.on('connection',(socket)=>{
    let name;
    socket.on('name message', (msg) => {
       name=msg;
       io.emit('name message', name+"已上线");
        socket.on("disconnect", (reason) => {
            io.emit('name message', name+"已断开");
        });
    });

    socket.on('chat message', (msg) => {
        io.emit('name message', name);
        io.emit('chat message', msg);
    });

})
server.listen(3000, () => {
    console.log('listening on *:3000');
});

实现方法

  • 需要先下载三方模块,实现双方同行主要依赖于这个模块npm i socket.io
  • 对于客户端分为发送信息和接收信息
  • 发送请求,当监听到提交事件后,拿到文本框内容,通过socket.emit()向服务端发送信息,这里参数为事件名,传输内容,这里还有一个可选的回调函数
  • 接受信息,socket.on()监听服务端发送过来的信息,这里参数为事件名,回调函数,服务端信息保存在回调函数里,通过创建一个li然后将服务端发的信息赋给li,再渲染到页面
  • 对于服务端当用户上线或者下线时向所有用户发送提示信息和实时接受信息并发送给所有用户
  • 引入socket.io模块后,需要将模块中的Srever结构出来,然后将原生http请求服务注册在socket的服务中
  • 当客户端默认请求时,将index.html也就是聊天界面发送个客户端
  • 客户端通过io.on(‘connection’,socket=>{})对服务端信息进行处理
  • socket.on(‘name message’, msg=>{})第一次上线发送
  • socket.on(“disconnect”,reason=>{})断开连接发送
  • socket.on(‘chat message’,msg=>{})实时处理客户端发送的信息

 到此这篇关于node.js用Socket.IO做聊天软件的实现示例的文章就介绍到这了,更多相关node.js Socket.IO聊天内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.adminjs.cn!