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

时间:2024-11-24 12:41:30
  • JS部分<chatroom.js>
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>
<!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>