SocketIO
Socket.io is a common library in the industry, which can be used for real-time, two-way and event-based communication between browsers and servers.
Midway provides support and encapsulation for Socket.io, which can simply create a Socket.io service. This article demonstrates how to provide Socket.io service under Midway system.
Midway uses the latest Socket.io (v4.0.0) for development.
Related information:
Provide services
Description | |
---|---|
Can be used for standard projects | ✅ |
Can be used for Serverless | ❌ |
Can be used for integration | ✅ |
Contains independent main framework | ✅ |
Contains independent logs | ❌ |
Install dependency
Install Socket.io dependencies in existing projects.
$ npm i @midwayjs/socketio@3 --save
## optional dependencies
$ npm i @types/socket.io-client socket.io-client --save-dev
Or reinstall the following dependencies in package.json
.
{
"dependencies": {
"@midwayjs/socket.io": "^3.0.0",
// Client optional
"socket.io-client": "^4.4.1 ",
// ...
},
"devDependencies": {
// Client optional
"@types/socket.io-client": "^1.4.36 ",
// ...
}
}
Open the component
@midwayjs/socket.io
can be used as an independent main framework.
import { Configuration } from '@midwayjs/core';
import * as socketio from '@midwayjs/socketio';
@Configuration({
imports: [socketio]
// ...
})
export class MainConfiguration {
async onReady() {
// ...
}
}
It can also be attached to other main frameworks, such as @midwayjs/koa
.
import { Configuration } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as socketio from '@midwayjs/socketio';
@Configuration({
imports: [koa, socketio]
// ...
})
export class MainConfiguration {
async onReady() {
// ...
}
}
Directory structure
The following is the basic directory structure of the Socket.io project. Similar to traditional applications, we have created a socket
directory to store service codes for Soscket.io services.
.
├── package.json
├── src
│ ├── configuration.ts ## entry configuration file
│ ├── interface.ts
│ └── socket ## socket.io service file
│ └── hello.controller.ts