- 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()的第一个参数是事件名,事件名有一些是库里预先定好的可以比如
connect
和disconnect
等,其他的都可以自己定义。同时非常关键的一点,如果是想让html
和js
产生互动,就必须保持事件名的一致性
- 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>