【node.js】Midway.js使用Socket.IO搭建即时通讯

简单教程
服务端
依赖

"@midwayjs/socketio": "^3.3.5",

config.default.ts文件引入

import { 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'],
    },
  },
  }

新建文件

import {
  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;
  }
}

客户端
依赖

"socket.io-client": "^4.5.1",

响应逻辑逻辑

 let 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
    })

发送消息逻辑

    let 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
    )
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Node.js is a massively popular JavaScript library that lets you use JavaScript to easily program scalable network applications and web services. People approaching Node.js for the first time are often attracted by its efficiency, scalability, and the fact that it’s based on JavaScript, the language of the Web, which means that developers can use the same language to write backend code. Also, it’s increasingly being seen as a “modern” replacement for PHP in web development, which relies on fast-paced data exchange. The growing community and the large amount of available modules makes Node.js one of the most attractive development environments. This book takes a step-wise and incremental approach toward developing cross-platform mobile technologies using existing web technologies. This will allow you to truly understand and become proficient in developing cross-platform mobile applications with Node.js, Ionic Framework, and MongoDB. The book starts off by introducing all the necessary requirements and knowledge to build a mobile application with a companion web service. It covers the ability to create an API from scratch and implement a comprehensive user database that will give you the opportunity to offer a mobile application with a personalized experience. Midway through the book, you will learn the basic processes to create a successful mobile application. You will also gain higher-level knowledge, allowing you to develop a functional and secure mobile application to ensure a seamless user experience for end users. Finally, the book ends with more advanced projects, which will bring together all the knowledge and expertise developed in the previous chapters to create a practical and functional mobile-application that has useful real-world features.
好的,使用 Midway 可以更方便地处理文件上传和保存。以下是一个基于 Midway 的示例,演示了如何解码并保存上传的图像数据到数据库中。 首先,您需要安装 `@midwayjs/koa` 和 `@midwayjs/socketio` 依赖,这里使用 Koa 框架和 Socket.IO 实现文件上传和实时通信: ```sh npm install @midwayjs/koa @midwayjs/socketio --save ``` 然后,您需要定义一个路由处理程序,处理上传的文件并将其保存到数据库中。以下是一个示例控制器,定义了一个 `upload` 方法来处理文件上传: ```typescript import { Provide, Inject } from '@midwayjs/decorator'; import { Context } from '@midwayjs/koa'; import { createReadStream } from 'fs'; import { join } from 'path'; import { v4 as uuid } from 'uuid'; import * as sharp from 'sharp'; import { UserService } from '../service/UserService'; @Provide() export class UserController { @Inject() userService: UserService; async upload(ctx: Context) { const { file } = ctx.request.files; const ext = file.name.substring(file.name.lastIndexOf('.')); const filename = uuid() + ext; const filepath = join(__dirname, '..', 'public', 'images', filename); // 解码并保存图像文件 const buffer = await sharp(createReadStream(file.path)).toBuffer(); await this.userService.saveImage(buffer, filename); // 返回图像 URL ctx.body = { url: `/images/${filename}` }; } } ``` 在 `upload` 方法中,首先从请求中获取上传的文件,然后使用 `sharp` 库将文件解码为图像数据。接下来,您可以使用 `UserService` 将图像数据保存到数据库中,最后返回图像 URL。 注意,此处使用了 `@midwayjs/decorator` 和 `@midwayjs/di` 来进行依赖注入,您需要在项目中安装这些依赖。另外,`sharp` 库用于图像处理和解码,您需要安装它。 定义 `UserService`,实现 `saveImage` 方法来保存图像到数据库中: ```typescript import { Provide } from '@midwayjs/decorator'; import { InjectEntityModel } from '@midwayjs/orm'; import { Repository } from 'typeorm'; import { Image } from '../entity/Image'; @Provide() export class UserService { @InjectEntityModel(Image) imageRepository: Repository<Image>; async saveImage(buffer: Buffer, filename: string) { const image = new Image(); image.data = buffer; image.filename = filename; await this.imageRepository.save(image); } } ``` 在 `saveImage` 方法中,创建一个 `Image` 实体,将图像数据存储在 `data` 字段中,将文件名存储在 `filename` 字段中,最后使用 `imageRepository` 保存实体到数据库中。 最后,您需要在应用程序中配置文件上传中间件和路由。以下是一个示例 `app.ts` 文件,配置了文件上传中间件和 `/api/user/upload` 路由: ```typescript import { Configuration } from '@midwayjs/decorator'; import { ILifeCycle, IMidwayApplication } from '@midwayjs/core'; import { createConnection } from '@midwayjs/orm'; import * as orm from '@midwayjs/orm'; import { join } from 'path'; import * as socketio from 'socket.io'; import * as cors from '@koa/cors'; import * as bodyParser from 'koa-body'; import { UserController } from './controller/UserController'; @Configuration({ imports: [orm], importConfigs: [join(__dirname, 'config')], }) export class ContainerLifeCycle implements ILifeCycle { async onReady(app: IMidwayApplication) { await createConnection(app.getConfig('orm')); const io = socketio(app.getServer()); io.on('connection', (socket) => { console.log('Socket connected:', socket.id); }); app .use(cors()) .use(bodyParser({ multipart: true })) .useStaticAssets({ root: join(__dirname, '..', 'public'), prefix: '/images', }) .useControllers(UserController); } } ``` 在 `onReady` 方法中,创建数据库连接,创建 Socket.IO 实例,配置文件上传中间件和静态文件服务,最后将路由控制器添加到应用程序中。 现在,您可以使用 Midway 进行文件上传和图像解码并将其保存到数据库中。在 Vue 前端应用程序中,您可以使用 axios 或其他库发送文件到服务器,并在成功上传后显示图像。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淡忘_cx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值