简单教程
服务端
依赖
复制代码
1
2"@midwayjs/socketio": "^3.3.5",
config.default.ts文件引入
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import { createRedisAdapter } from '@midwayjs/socketio'; export default { socketIO: { adapter: createRedisAdapter({ host: '127.0.0.1', port: 6379, }), path: '/socketio', transports: ['polling', 'websocket'], cors: { origin: '*', methods: ['GET', 'POST'], }, }, }
新建文件
复制代码
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
36
37
38
39
40
41
42
43
44
45
46
47import { WSController, OnWSConnection, Inject, OnWSMessage, WSEmit, } from '@midwayjs/decorator'; import { Context } from '@midwayjs/socketio'; /** * 测试 */ @WSController('/') export class HelloController { @Inject() ctx: Context; // 客户端连接 @OnWSConnection() async onConnectionMethod() { console.log('on client connect', this.ctx.id); console.log('参数', this.ctx.handshake.query); this.ctx.join('fz' + this.ctx.handshake.query.fjh); let data2 = { id: this.ctx.id, fj: this.ctx.handshake.query.fjh, data: null, xx: this.ctx.handshake.query, }; this.ctx.emit('data', data2, '连接成功'); } // 消息事件 @OnWSMessage('data') @WSEmit('data') async gotMessage(data) { let data2 = { id: this.ctx.id, fj: this.ctx.handshake.query.fjh, data: data, xx: this.ctx.handshake.query, }; // console.log('on data got', this.ctx.id, data2); // this.ctx.broadcast.emit('data', data); this.ctx.to('fz' + this.ctx.handshake.query.fjh).emit('data', data2); // this.ctx.to('polling').emit('data', data); return data2; } }
客户端
依赖
复制代码
1
2"socket.io-client": "^4.5.1",
响应逻辑逻辑
复制代码
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
26let socket = io(import.meta.env.VITE_APP_URL_WSS + '/?fjh=' + fjh2.value + '&name=' + nane2.value, { path: '/socketio', // 这里是客户端的 path transports: ['websocket'], secure: true }) console.log(socket) socket.on('data', msg => { if (msg.data != null) { let data3 = { name: msg.xx.name, xx: msg.data, id: msg.id, fj: msg.xx.fjh } data2.push(data3) } console.log('服务端消息', msg, data2) }) socket.on('connect', () => { console.log(socket.connected) // true }) socket.on('disconnect', () => { console.log(socket.connected) // false })
发送消息逻辑
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13let socket = io(import.meta.env.VITE_APP_URL_WSS + '/?fjh=' + fjh2.value + '&name=' + nane2.value, { path: '/socketio', // 这里是客户端的 path transports: ['websocket'], secure: true }) console.log(data.value, '09') socket.emit('data', data.value ) }
最后
以上就是整齐帅哥最近收集整理的关于【node.js】Midway.js使用Socket.IO搭建即时通讯的全部内容,更多相关【node内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复