目标
用户与服务端建立通信,服务端能检测到用户端的连接信息
代码
- 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')
socket.on('disconnect',()=>{
console.log("an user disconnected")
})
}
)
const port =3001
server.listen(port,()=>{
console.log(`server is running at http://localhost:${port}`)\\反引号字符串模板
})
- Html部分<
index.html
>
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>\\不能遗漏,这里是让浏览器提前加载socket.io库
</head>
<body>
<h1>Chat Room</h1>
<input id="inputtext" placeholder="Enter your message">
<button id="inputbtn">Send</button>
<script>
const socket = io()\\浏览器与服务端建立连接的关键
</script>
</body>
</html>
效果
- JS部分
输入node chatroom.js
运行
- Html部分