一、NestJs WebSocket

  1. 安装依赖
    npm i --save @nestjs/websockets @nestjs/platform-socket.io
    npm i ws
  2. 新建ws.gateway.ts文件
import {ConnectedSocket,MessageBody,SubscribeMessage,WebSocketGateway,
} from '@nestjs/websockets';
import * as WebSocket from 'ws';@WebSocketGateway(17030)
export class WsStartGateway {@SubscribeMessage('hello')hello(@MessageBody() data: string): string {return data;}@SubscribeMessage('hello2')hello2(@MessageBody() data: string,@ConnectedSocket() client: WebSocket,): string {console.log('收到消息 client:', client);// client.send(JSON.stringify({ event: 'tmp', data: '这里是个临时信息' }));return data;}
}
  1. 把WsStartGateway放到AppModule的providers里
import { WsStartGateway } from './component/ws/ws.gateway';
@Module({providers: [AppService, WsStartGateway],
})
  1. 自定义适配器(WebSocketAdapter) ,新建一个ws.adapter.ts文件
import * as WebSocket from 'ws';
import { WebSocketAdapter, INestApplicationContext } from '@nestjs/common';
import { MessageMappingProperties } from '@nestjs/websockets';
import { Observable, fromEvent, EMPTY } from 'rxjs';
import { mergeMap, filter } from 'rxjs/operators';export class WsAdapter implements WebSocketAdapter {constructor(private app: INestApplicationContext) {}create(port: number, options: any = {}): any {console.log('ws create');return new WebSocket.Server({ port, ...options });}bindClientConnect(server, callback: Function) {console.log('ws bindClientConnect, server:\n', server);server.on('connection', callback);}bindMessageHandlers(client: WebSocket,handlers: MessageMappingProperties[],process: (data: any) => Observable<any>,) {console.log('[waAdapter]有新的连接进来');fromEvent(client, 'message').pipe(mergeMap((data) =>this.bindMessageHandler(client, data, handlers, process),),filter((result) => result),).subscribe((response) => client.send(JSON.stringify(response)));}bindMessageHandler(client: WebSocket,buffer,handlers: MessageMappingProperties[],process: (data: any) => Observable<any>,): Observable<any> {let message = null;try {message = JSON.parse(buffer.data);console.log(message);} catch (error) {console.log('ws解析json出错', error);return EMPTY;}const messageHandler = handlers.find((handler) => {return handler.message === message.event;});if (!messageHandler) {return EMPTY;}return process(messageHandler.callback(message.data));}close(server) {console.log('ws server close');server.close();}
}
  1. 在main.ts里使用这个适配器
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from './ws/ws.adapter';async function bootstrap() {const app = await NestFactory.create(AppModule);app.useWebSocketAdapter(new WsAdapter(app)); // 使用我们的适配器await app.listen(3001);
}
bootstrap();
  1. ws://localhost:17030

二、Vue WebSocket

  1. socket.js
import { Message } from 'hui';class MessageSocket {constructor () {this.ws = nullthis.socketStatus = false}connect() {this.ws = new WebSocket('ws://localhost:17030')this.ws.onopen = this.onopen.bind(this)this.ws.onmessage = this.onmessage.bind(this)this.ws.onclose = this.onclose.bind(this)this.ws.onerror = this.onerror.bind(this)}onopen() {this.socketStatus = trueconsole.log('websocket连接成功!', this.ws)}onmessage(e) {console.log('xia', e)console.log(JSON.parse(e.data))}onclose() {this.socketStatus = falseconsole.log('websocket连接关闭.')}onerror() {console.log(e)this.socketStatus = falseMessage.error({showClose: true,message: 'websocket连接失败',duration: 0})}send(message) {if(this.ws && this.socketStatus) {this.ws.send(JSON.stringify(message))console.log('发送成功', JSON.stringify(message))}}
}const messageSocket = new MessageSocket()export default messageSocket
  1. 发送消息
import messageSocket from './socket'
messageSocket.connect()
messageSocket.send({event: 'hello',data: 'xia xin'
})

NestJs WebSocket与Vue WebSocket相关推荐

  1. vue+websocket+express+mongodb实战项目(实时聊天)(一)

    ##vue+websocket+express+mongodb实战项目(实时聊天)(一) 在原来基础上增加了多个聊天室以及发送图片[vue+websocket+express+mongodb实战项目( ...

  2. Springboot+vue+websocket 实现前后台主动通信

    后端springboot: pom <dependencies><dependency><groupId>org.springframework.boot</ ...

  3. 什么是WebSocket?WebSocket在Vue中如何使用?

    什么是WebSocket?WebSocket在Vue中如何使用? 什么是Websocket?   通俗说, WebSocket是一种数据通信协议,用于客户端和服务端数据通信.类似于http协议,但ht ...

  4. vue+websocket+Stomp组件实现前端长连接

    1文件结构 2.重点文件夹中的文件代码以及作用 ① 根目录中systemConfig文件夹中的main.js文件 /***作用:作为项目中的配置文件,放了websocket连接的url,用户名(adm ...

  5. Spring clound+VUE+WebSocket实现消息推送 一(即时通讯)

    需求: 当用户进行某个操作,需要通知其他用户时,其他用户可以实时接收消息. 工程为 Spring cloud + VUE . 技术实现: Spring Cloud.Spring boot.vue.we ...

  6. 【系统开发】WebSocket + SpringBoot + Vue 搭建简易网页聊天室

    文章目录 一.数据库搭建 二.后端搭建 2.1 引入关键依赖 2.2 WebSocket配置类 2.3 配置跨域 2.4 发送消息的控制类 2.5 R类 三.前端搭建 3.1 自定义文件websock ...

  7. 电子信息毕业设计VUE+websocket+Echart+服务器的智能农业管理系统

    目录 一.作品介绍 二.开发环境 三.系统功能截图 1.登录界面 2.设备管理 3.配置管理界面 4.历史数据 5.数据分析 6. 权限管理 7.远程管理 四.部分关键代码 一.作品介绍 现在农业在互 ...

  8. WebSocket + SpringBoot + VUE实现后端实时向前端推送消息

    一.目的 众所周知,正常来说在前后端通信中,后端往往处于一个被动的状态,对前端的请求作出对应的响应.但有的时候我们会遇到需要后端前前端推送数据的需求,比如消息.邮件等的推送.这个时候,实现的一种方式是 ...

  9. websocket之一:websocket简介

    Websocket websocket为一次HTTP握手后,后续通讯为tcp协议的通讯方式. WebSocket 使用一种被称作"Upgrade handshake(升级握手)"的 ...

最新文章

  1. 使用 XSL 样式表无法查看 XML 输入。请更正错误然后单击 刷新按钮,或以后重试。...
  2. 算法炒房三月亏20多亿。房地产巨头大翻车:房价水太深,AI根本把握不住
  3. 单身的我听着单身情歌。。。看着那些儿时看过的小说。。。
  4. socket编程中常见的概念问题!
  5. jupyter下使用conda环境
  6. 布隆过滤器(Bloom Filter)的原理和实现
  7. iOS开发~UI布局(二)storyboard中autolayout和size class的使用详解
  8. 朴素贝叶斯算法--过滤垃圾短信
  9. 终于有人把Knative讲明白了
  10. 高可用高性能负载均衡软件HAproxy详解指南-第一章(简介、安装)
  11. Python的is和==区别
  12. PyHook3简明教程
  13. 仅此一文,看懂二极管的所有基础知识点
  14. 【每周论文】Graphene: Packing and Dependency-aware Scheduling for Data-Parallel Clusters(OSDI 2016)
  15. 项目 | Java+PhantomJs爬虫实战——半次元 下载高清原图
  16. 「GoTeam 招聘时间」深信服科技 Go 开发工程师(成都)
  17. mysql 索引的模糊查询_MYSQL语法(模糊查询,视图,索引)
  18. 2021秋季《数据结构》_EOJ 1063.树的双亲存储法(parent+child / parent)
  19. 人像美妆---妆容迁移算法研究(Makeup transfer)
  20. BitComet 0.90 ED下载功能的插件下载地址

热门文章

  1. 华为HUAWEI交换机堆叠
  2. 利用python脚本一键为MySQL插入万条数据
  3. 记一次java代码连接orcal数据库查视图报 java.sql.SQLSyntaxErrorException: ORA-00942: 表或视图不存在
  4. af if no sooner than..
  5. 使用Beanstalk搭建队列服务
  6. [WTL/ATL]_[初级]_[设置超链接字体颜色]
  7. 串口 COM口 TTL RS-232 RS-485 区别(转载)
  8. FFmpeg学习(1)开篇
  9. 莎士比亚十四行诗第六七首
  10. 爬虫学习-数据解析三种方式:正则、bs4、xpath,以及一些实例操作