经过短暂的研究 NestJS。这是我的解决方案。
src
├── app.controller.spec.ts
├── app.controller.ts
├── app.module.ts
├── common
│ └── adapters
│ └── ws-adapter.ts
├── events
│ ├── events.gateway.ts
│ └── events.module.ts
└── main.ts
main.ts
文件
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from './common/adapters/ws-adapter.ts';
import * as cors from 'cors';
let corsOptions = {
origin: 'http://nestjs.test',
credentials: true
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(new WsAdapter(3000));
app.use(cors(corsOptions));
await app.listen(4000);
}
bootstrap();
因为当我们使用 WebSocket 适配器时,我们不能再使用与 NestJS 应用程序相同的端口了。
common\adapters\ws-adapter.ts
文件
import * as WebSocket from 'ws';
import { WebSocketAdapter } from '@nestjs/common';
import { IoAdapter } from '@nestjs/websockets';
import { MessageMappingProperties } from '@nestjs/websockets';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/filter';
export class WsAdapter extends IoAdapter {
public bindMessageHandlers(
client,
handlers: MessageMappingProperties[],
process: (data: any) => Observable<any>,
) {
handlers.forEach(({ message, callback }) => {
client.on('event', function (data, ack) {
console.log('DATA', data)
ack('woot')
})
Observable.fromEvent(client, message)
.switchMap(data => process(callback(data)))
.filter(result => !!result && result.event)
.subscribe(({ event, data }) => client.emit(event, data))
});
}
}
我的客户端源代码
socket.emit('event', {data: 'some data'}, function (response) {
console.log('RESPONSE', response)
});
socket.on('event', function(data) {
console.log('ON EVENT', data);
});
这是我的结果
希望这有帮助!!