├── node_modules # 第三⽅包存储⽬录
├── index.js # node启动文件
├── index.html # 测试socket
├── yarn.json # 记录安装时的包的版本号,以保证⾃⼰或其他⼈在 yarn 时⼤家的依赖能保证⼀致
└── package.json # 包说明⽂件,记录了项⽬中使⽤到的第三⽅包依赖信息等内容
mkdir scoket-chat-back
cd scoket-chat-back
使用 yarn 或者 npm 初始化项目
yarn
yarn init -y
npm
npm init -y
yarn add socket.io express
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require('socket.io');
const io = new Server(server);
let rooms = {};
io.on('connection', (socket) => {
console.log('a user connected');
// 接收`send`事件传递过来的消息
socket.on('send', (data) => {
console.log(data);
// 将内容发送到`receive`
socket.emit('receive', data);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
/>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Documenttitle>
head>
<body>body>
<script type="module">
import { io } from 'https://cdn.socket.io/4.4.1/socket.io.esm.min.js';
const socket = io('http://localhost:3000', {
transports: ['websocket'],
});
// 监听客户端连接,回调函数会传递本次连接的socket
socket.on('connect', () => {
console.log('#connect,', socket.id);
// 发送消息
socket.emit('send', 'hello word!');
// 接收消息
socket.on('receive', (data) => {
console.log(data);
});
});
script>
html>
服务端
控制台输出a user connected
和hello word!
则代表我们已经连接成功,并成功接收到消息
客户端
控制台输出#connect, 89_-7lb-VzJtNDjXAAAH
和hello word!
则代表我们已经连接成功,并成功接收到消息