Node.js笔记(四)局域网聊天室2:服务端接受客户端消息

目标

客户端服务端建立连接加载,服务端能接受客户端传过来的消息

代码

  • JS部分<chatroom.js>
javascript 复制代码
const express = require('express')
const http = require('http')
const {Server} = require('socket.io')

const app = express()
const server = http.createServer(app)
const io = new Server(server)

app.use(express.static(__dirname))
io.on('connect',(socket)=>{
    console.log('an user connected')
    \\监听客户端的信息,注意函数的第一个事件参数名要与Html部分里的事件名保持一致
    socket.on('chat message',(msg)=>{
        console.log('Message received:',msg)
    })
    socket.on('disconnect',()=>{
        console.log("an user disconnected")
    })
}
    
)

const port =3001
server.listen(port,()=>{
    console.log(`server is running at http://localhost:${port}`)
})

socket.on()的第一个参数是事件名,事件名有一些是库里预先定好的可以比如connectdisconnect等,其他的都可以自己定义。同时非常关键的一点,如果是想让htmljs产生互动,就必须保持事件名的一致性

  • Html部分<index.html>
html 复制代码
<!DOCTYPE html>
<html>
    <head>
        <script src="/socket.io/socket.io.js"></script>
    </head>
    <body>
        <h1>Chat Room</h1>
        <input id="inputtext" placeholder="Enter your message">
        <button id="sendbtn">Send</button>
        <script>
            const socket = io()
            const input = document.getElementById('inputtext')
            const sendbtn = document.getElementById('sendbtn')
            sendbtn.addEventListener("click",()=>{
                const message = input.value
                if(message){
                    socket.emit("chat message",message)
                    input.value=''
                }
            })
            socket.on('chat message',(msg)>{

            })
        </script>
    </body>
</html>

效果

  • JS部分<chatroom.js>

  • Html部分<index.html>

相关推荐
叫我Paul就好9 小时前
尝试 Node 搭建后端-开发框架
node.js
风止何安啊2 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js
糖拌西瓜皮2 天前
Node.js核心模块实战:文件、路径、HTTP与流处理
javascript·node.js
糖拌西瓜皮2 天前
Node.js工程化实践:包管理、TypeScript配置与代码质量
typescript·node.js
糖拌西瓜皮2 天前
NestJS入门指南:Java开发者的Spring Boot体验
javascript·node.js
糖拌西瓜皮2 天前
Express框架快速上手:中间件、路由与错误处理
javascript·node.js
半个落月2 天前
从 Tokenization 到 Embedding:用 Node.js 搞懂大模型为什么先“分词”再“向量化”
人工智能·node.js
叁两3 天前
前端转型AI Agent该如何学习?(前置篇)
前端·人工智能·node.js
糖拌西瓜皮3 天前
TypeScript 进阶:泛型、条件类型、类型守卫与装饰器
javascript·node.js
LinXunFeng5 天前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github