node.js: socket.io服务端和客户端交互示例
【摘要】
实现效果 文档:
https://socket.io/
安装依赖
npm install express socket.io
1
修改 package.json
"type": "module...
实现效果
文档:
安装依赖
npm install express socket.io
- 1
修改 package.json
"type": "module",
- 1
服务端代码
// server.js
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import path from "path";
const __dirname = path.resolve();
const app = express();
const server = createServer(app);
const io = new Server(server);
// http
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
// websocket
io.on("connection", (client) => {
console.log("socket connection");
// 消息发送
client.on("chat message", (msg) => {
io.emit("chat message", msg);
});
// 断开连接
client.on("disconnect", () => {
console.log("socket disconnect");
});
});
server.listen(3000, () => {
console.log("server start");
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
客户端代码
<!-- index.html -->
<!-- 消息输入 -->
<form id="form">
<input id="input" type="text" />
<button>发送</button>
</form>
<!-- 消息显示 -->
<div id="message-list"></div>
<script src="socket.io/socket.io.js"></script>
<script>
const form = document.querySelector("#form");
const input = document.querySelector("#input");
const messageList = document.querySelector("#message-list");
const socket = io();
// 发送消息
form.addEventListener("submit", function (event) {
event.preventDefault();
if (input.value) {
socket.emit("chat message", input.value);
input.value = "";
}
});
// 接收消息
socket.on("chat message", (msg) => {
const li = document.createElement("li");
li.textContent = msg;
messageList.appendChild(li);
});
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/126009476
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)