Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
node
/
app-admin
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 83be0ccc
authored
Sep 16, 2024
by
yixinjj
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
添加发送ws消息到客户端
1 parent
4be6f62c
Hide whitespace changes
Inline
Side-by-side
Showing
19 changed files
with
114 additions
and
88 deletions
package.json
src/app.module.ts
src/common/enums/index.ts
src/common/filters/exception.filter.ts
src/common/filters/http-exception.filter.ts
src/main.ts
src/modules/broadcast/broadcast.controller.ts
src/modules/broadcast/broadcast.module.ts
src/modules/broadcast/broadcast.service.ts
src/modules/ws/ws.gateway.ts
src/modules/ws/ws.module.ts
src/modules/ws/ws.service.ts
src/types/broadcast.d.ts
src/types/common.d.ts
src/types/device.d.ts
src/types/ws.d.ts
test.html
test.http
yarn.lock
package.json
View file @
83be0cc
...
...
@@ -64,7 +64,7 @@
"redis"
:
"^4.7.0"
,
"reflect-metadata"
:
"^0.1.13"
,
"rimraf"
:
"^3.0.2"
,
"rxjs"
:
"^
6.5.4
"
,
"rxjs"
:
"^
7.8.1
"
,
"socket.io"
:
"4.7.4"
,
"swagger-ui-express"
:
"^4.1.4"
,
"typeorm"
:
"^0.2.25"
,
...
...
src/app.module.ts
View file @
83be0cc
...
...
@@ -20,6 +20,7 @@ import { FileModule } from './modules/file/file.module'
import
{
WsModule
}
from
'./modules/ws/ws.module'
// import { WsGateway } from './modules/ws/ws.gateway';
import
{
SseModule
}
from
'./modules/sse/sse.module'
import
{
BroadcastModule
}
from
'./modules/broadcast/broadcast.module'
@
Module
({
imports
:
[
...
...
@@ -46,7 +47,8 @@ import { SseModule } from './modules/sse/sse.module'
// UsersModule,
FileModule
,
SseModule
,
WsModule
WsModule
,
BroadcastModule
],
})
export
class
AppModule
{
...
...
src/common/enums/index.ts
View file @
83be0cc
...
...
@@ -18,4 +18,14 @@
SUCCESS
=
'请求成功'
,
FAILURE
=
'请求失败'
,
}
\ No newline at end of file
export
enum
WsMessageType
{
/**
* 私有订阅
*/
Private
=
'private'
,
/**
* 系统订阅
*/
System
=
'system'
}
\ No newline at end of file
src/common/filters/exception.filter.ts
View file @
83be0cc
...
...
@@ -11,7 +11,7 @@ export class ExceptionsFilter implements ExceptionFilter {
// 获取响应体
const
response
=
ctx
.
getResponse
<
Response
>
()
const
request
=
ctx
.
getRequest
<
Request
>
()
console
.
log
(
exception
)
console
.
log
(
1
,
exception
)
// 获取状态码,判断是HTTP异常还是服务器异常
const
statusCode
=
exception
instanceof
HttpException
?
exception
.
getStatus
()
:
HttpStatus
.
INTERNAL_SERVER_ERROR
const
msg
=
exception
instanceof
HttpException
?
exception
.
message
:
'服务器异常'
...
...
src/common/filters/http-exception.filter.ts
View file @
83be0cc
...
...
@@ -8,7 +8,7 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
const
response
=
ctx
.
getResponse
<
Response
>
()
const
request
=
ctx
.
getRequest
<
Request
>
()
const
status
=
exception
.
getStatus
()
console
.
log
(
exception
)
console
.
log
(
2
,
exception
)
const
exceptionRes
:
any
=
exception
.
getResponse
()
const
{
message
}
=
exceptionRes
...
...
src/main.ts
View file @
83be0cc
...
...
@@ -17,7 +17,11 @@ async function bootstrap() {
// 全局过滤器
app
.
useGlobalFilters
(
new
ExceptionsFilter
())
app
.
useGlobalFilters
(
new
HttpExceptionFilter
())
app
.
enableCors
()
app
.
enableCors
({
allowedHeaders
:
'*'
,
origin
:
'*'
,
credentials
:
true
,
})
const
redisIoAdapter
=
new
RedisIoAdapter
(
app
);
await
redisIoAdapter
.
connectToRedis
();
app
.
useWebSocketAdapter
(
redisIoAdapter
);
...
...
src/modules/broadcast/broadcast.controller.ts
View file @
83be0cc
import
{
Controller
,
Post
,
Body
,
UseInterceptors
}
from
'@nestjs/common'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
TransformInterceptor
}
from
'../../common/interceptors'
import
{
WsGateway
}
from
'../ws/ws.gateway'
;
@
Controller
(
'broadcast'
)
@
UseInterceptors
(
TransformInterceptor
)
export
class
BroadcastController
{
constructor
(
private
readonly
broadcastService
:
BroadcastService
){}
constructor
(
private
readonly
broadcastService
:
BroadcastService
,
private
readonly
wsGateway
:
WsGateway
){}
//写一个message方法 接收params参数 然后调用broadcastService的message方法
@
Post
(
'message'
)
message
(@
Body
()
params
:
any
)
{
// return this.broadcastService.message
(params)
@
Post
(
'
/
message'
)
async
message
(@
Body
()
params
):
Promise
<
any
>
{
return
this
.
wsGateway
.
send
(
params
)
}
}
src/modules/broadcast/broadcast.module.ts
View file @
83be0cc
...
...
@@ -2,10 +2,10 @@ import { Module } from '@nestjs/common'
import
{
BroadcastController
}
from
'./broadcast.controller'
import
{
BroadcastService
}
from
'./broadcast.service'
import
{
WsModule
}
from
'../ws/ws.module'
;
import
{
WsService
}
from
'../ws/ws.service'
;
@
Module
({
imports
:
[
WsModule
],
controllers
:
[
BroadcastController
],
providers
:
[
BroadcastService
]
providers
:
[
BroadcastService
,
WsService
]
})
export
class
BroadcastModule
{}
src/modules/broadcast/broadcast.service.ts
View file @
83be0cc
import
{
Injectable
,
HttpException
,
HttpStatus
}
from
'@nestjs/common'
import
{
WsGateway
}
from
'../ws/ws.gateway'
;
@
Injectable
()
export
class
BroadcastService
{
constructor
(
private
readonly
wsGateway
:
WsGateway
)
{
}
// 广播消息
message
(
)
{
this
.
wsGateway
.
server
.
emit
(
'message'
,
'hello world'
)
}
//
constructor(private readonly wsGateway: WsGateway) { }
//
//
广播消息
// message(param:WsTypes.SendBody<WsTypes.MessageType>
) {
// return this.wsGateway.send(param
)
//
}
}
src/modules/ws/ws.gateway.ts
View file @
83be0cc
...
...
@@ -3,7 +3,10 @@ import { from, Observable } from 'rxjs'
import
{
map
}
from
'rxjs/operators'
import
{
Server
,
Socket
}
from
'socket.io'
import
{
WsService
}
from
'./ws.service'
import
{
Logger
}
from
'@nestjs/common'
import
{
Logger
,
Module
,
UseInterceptors
}
from
'@nestjs/common'
import
{
WsMessageType
}
from
'../../common/enums'
import
{
TransformInterceptor
}
from
'../..//common/interceptors'
/**
* WebSocket 网关
*
...
...
@@ -17,13 +20,14 @@ import { Logger } from '@nestjs/common'
methods
:
[
'GET'
,
'POST'
],
// 允许的 HTTP 请求类型
cors
:
true
// 允许跨域
})
export
class
WsGateway
implements
WsTypes
.
WebSocketGateway
<
Server
,
Observable
<
WsResponse
<
string
>>
,
any
>
,
OnGatewayConnection
,
OnGatewayDisconnect
,
OnGatewayInit
{
@
UseInterceptors
(
TransformInterceptor
)
export
class
WsGateway
implements
WsTypes
.
WebSocketGateway
<
Server
,
Observable
<
WsResponse
<
string
>>
,
any
>
,
OnGatewayConnection
,
OnGatewayDisconnect
,
OnGatewayInit
{
/**
* 用于初始化私有订阅消息处理类的构造函数。
*
* @param wsService - 注入的 WebSocket 服务实例,用于处理 WebSocket 相关操作。
*/
constructor
(
p
rivate
readonly
wsService
:
WsService
)
{}
constructor
(
p
ublic
readonly
wsService
:
WsService
)
{}
/**
* WebSocket 服务器实例
*/
...
...
@@ -34,8 +38,8 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server,Observable<WsR
* @param data - 传入的数据
* @returns 包含事件和数据的 Observable 对象
*/
@
SubscribeMessage
(
Ws
Types
.
MessageType
.
Private
)
subPrivate
(@
MessageBody
()
data
:
any
):
Observable
<
WsResponse
<
string
>>
{
@
SubscribeMessage
(
WsMessageType
.
Private
)
subPrivate
(@
MessageBody
()
data
:
any
):
Observable
<
WsResponse
<
string
>>
{
return
from
<
string
>
(
'hello'
).
pipe
(
map
(
item
=>
({
event
:
'events'
,
data
:
item
})))
}
...
...
@@ -44,7 +48,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server,Observable<WsR
* @param data - 传入的数据
* @returns 包含事件和数据的 Observable 对象
*/
@
SubscribeMessage
(
Ws
Types
.
MessageType
.
System
)
@
SubscribeMessage
(
WsMessageType
.
System
)
async
subSystem
(@
MessageBody
()
data
:
number
):
Promise
<
number
>
{
return
data
}
...
...
@@ -79,4 +83,12 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server,Observable<WsR
// 重置 socketIds
this
.
wsService
.
resetClients
()
}
public
send
(
payload
:
WsTypes
.
MessageBody
):
Promise
<
any
>
{
if
(
payload
.
event
===
WsMessageType
.
Private
)
{
return
this
.
wsService
.
sendPrivateMessage
(
payload
)
}
else
{
return
this
.
wsService
.
sendPublicMessage
(
payload
)
}
}
}
src/modules/ws/ws.module.ts
View file @
83be0cc
...
...
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import
{
WsGateway
}
from
'./ws.gateway'
;
import
{
WsService
}
from
'./ws.service'
;
@
Module
({
providers
:
[
WsGateway
,
WsService
],
exports
:
[
WsGateway
],
...
...
src/modules/ws/ws.service.ts
View file @
83be0cc
import
{
Injectable
}
from
'@nestjs/common'
import
{
HttpException
,
HttpStatus
,
Injectable
}
from
'@nestjs/common'
import
{
Server
,
Socket
}
from
'socket.io'
import
{
Logger
}
from
'@nestjs/common'
// import { WSResponse } from '../message/model/ws-response.model';
// import { validateToken } from '@/utils/helper';
// import { Message } from '@/entities/message.entity';
// import { User } from '@/entities/user.entity';
import
{
WsMessageType
}
from
'../../common/enums'
@
Injectable
()
export
class
WsService
{
constructor
()
{}
...
...
@@ -28,7 +28,7 @@ export class WsService {
return
}
// 认证用户
const
res
=
{
employeeId
:
1
+
''
}
//JwtInterface = validateToken(token.replace('Bearer ', ''))
const
res
=
client
.
handshake
?.
auth
//
{ employeeId: 1 + '' } //JwtInterface = validateToken(token.replace('Bearer ', ''))
if
(
!
res
)
{
Logger
.
error
(
'token 验证不通过'
)
client
.
send
(
'token 验证不通过'
)
...
...
@@ -45,12 +45,12 @@ export class WsService {
const
clients
:
Map
<
string
,
Socket
>
=
this
.
server
.
sockets
.
sockets
const
clientIsOnline
:
Socket
=
clients
.
get
(
this
.
clientIds
.
get
(
employeeId
))
// 处理同一工号在多处登录
clientIsOnline
?.
send
(
`
${
employeeId
}
已在别处上线, 此客户端下线处理`
)
clientIsOnline
?.
emit
(
WsMessageType
.
System
,
`
${
employeeId
}
已在别处上线, 此客户端下线处理`
)
clientIsOnline
?.
disconnect
()
// 保存工号
this
.
clientIds
.
set
(
employeeId
,
client
.
id
)
Logger
.
log
(
`
${
employeeId
}
connected, onLine:
${
clients
.
size
}
`
)
this
.
server
.
send
(
`
${
employeeId
}
connected, onLine:
${
clients
.
size
}
`
)
this
.
server
.
emit
(
WsMessageType
.
System
,
`
${
employeeId
}
connected, onLine:
${
clients
.
size
}
`
)
return
}
...
...
@@ -79,10 +79,11 @@ export class WsService {
* @param messagePath 发布地址
* @param response 响应数据
*/
async
sendPublicMessage
(
data
:
WsTypes
.
SystemData
)
{
const
res
=
this
.
server
?.
emit
(
WsTypes
.
MessageType
.
System
,
data
)
async
sendPublicMessage
(
payload
:
WsTypes
.
MessageBody
)
{
console
.
log
(
'websocket send'
,
payload
)
const
res
=
this
.
server
?.
emit
(
WsMessageType
.
System
,
payload
.
data
)
if
(
!
res
)
{
Logger
.
log
(
'websocket send error'
,
data
)
Logger
.
log
(
'websocket send error'
,
payload
)
}
}
...
...
@@ -92,19 +93,13 @@ export class WsService {
* @param response 响应数据
* @param employeeId 接收者工号
*/
async
sendPrivateMessage
(
data
:
WsTypes
.
PrivateData
)
{
const
client
=
this
.
server
.
sockets
.
sockets
.
get
(
this
.
clientIds
.
get
(
data
.
employeeId
))
const
res
=
client
?.
emit
(
WsTypes
.
MessageType
.
Private
,
data
)
async
sendPrivateMessage
(
payload
:
WsTypes
.
MessageBody
)
{
console
.
log
(
'websocket send'
,
payload
)
if
(
!
payload
.
employeeId
)
throw
new
HttpException
({
status
:
HttpStatus
.
BAD_REQUEST
,
message
:
'请求参数employeeId 必传'
,
error
:
'employeeId is required'
},
HttpStatus
.
BAD_REQUEST
)
const
client
=
this
.
server
.
sockets
.
sockets
.
get
(
this
.
clientIds
.
get
(
payload
.
employeeId
))
const
res
=
client
?.
emit
(
WsMessageType
.
Private
,
payload
.
data
)
if
(
!
res
)
{
Logger
.
log
(
'websocket send error'
,
data
)
}
}
send
(
payload
:
WsTypes
.
SendBody
<
WsTypes
.
MessageType
>
)
{
if
(
payload
.
event
===
WsTypes
.
MessageType
.
Private
)
{
this
.
sendPrivateMessage
(
payload
.
data
as
WsTypes
.
PrivateData
)
}
else
{
this
.
sendPublicMessage
(
payload
.
data
)
Logger
.
log
(
'websocket send error'
,
payload
)
}
}
}
src/types/broadcast.d.ts
View file @
83be0cc
declare
namespac
e
Broadcastypes
{
declare
modul
e
Broadcastypes
{
}
\ No newline at end of file
src/types/common.d.ts
View file @
83be0cc
/**
* 公共命名空间声明
*/
declare
namespac
e
CommonTypes
{
declare
modul
e
CommonTypes
{
/**
* 定义一个基本的响应对象接口
*/
...
...
src/types/device.d.ts
View file @
83be0cc
declare
namespac
e
DeviceTypes
{
declare
modul
e
DeviceTypes
{
/**
* 查询设备信息的查询对象接口
*
...
...
src/types/ws.d.ts
View file @
83be0cc
declare
namespac
e
WsTypes
{
declare
modul
e
WsTypes
{
abstract
class
WebSocketGateway
<
S
,
T
,
U
>
{
server
:
S
abstract
subPrivate
(
data
:
any
):
T
abstract
subSystem
(
data
:
U
):
Promise
<
U
>
}
type
WsMsgType
=
'private'
|
'system'
enum
MessageType
{
/**
* 私有订阅
*/
Private
=
'private'
,
/**
* 系统订阅
*/
System
=
'system'
}
interface
SystemData
{
[
key
:
string
]:
any
}
type
MessageBody
<
T
=
WsMsgType
>
=
{
event
:
T
data
:
any
}
&
(
T
extends
'private'
?
PrivateData
:
Partial
<
PrivateData
>
)
interface
PrivateData
extends
SystemData
{
interface
PrivateData
{
/**
* 接收者工号
*/
employeeId
:
string
}
interface
MessageDataMap
{
[
MessageType
.
Private
]:
PrivateData
[
MessageType
.
System
]:
SystemData
}
type
ConditionalData
<
T
extends
MessageType
>
=
T
extends
MessageType
?
MessageDataMap
[
T
]
:
never
// 最后,修改SendBody接口,使用ConditionalData来约束T
interface
SendBody
<
T
extends
MessageType
>
{
event
:
T
data
:
ConditionalData
<
T
>
}
}
test.html
View file @
83be0cc
...
...
@@ -53,15 +53,15 @@
// }
const
socket
=
io
(
'http://192.168.1.129:8080'
,{
auth
:
{
token
:
'12`13`23'
},
auth
:
{
token
:
'12`13`23'
,
employeeId
:
Math
.
random
()
+
''
},
});
socket
.
on
(
'connect'
,
function
(
a
)
{
console
.
log
(
'Connected'
);
console
.
log
(
socket
,
a
)
socket
.
emit
(
'private'
,
{
test
:
'test'
});
socket
.
emit
(
'system'
,
0
,
response
=>
console
.
log
(
'Identity:'
,
response
),
);
//
socket.emit('private', { test: 'test' });
//
socket.emit('system', 0, response =>
//
console.log('Identity:', response),
//
);
});
socket
.
on
(
'private'
,
function
(
data
)
{
console
.
log
(
'event'
,
data
);
...
...
test.http
View file @
83be0cc
http://localhost:3000/device?pageIndex=1&pageSize=1&user=李四
#
http://localhost:3000/device?pageIndex=1&pageSize=1&user=李四
# POST http://localhost:3000/device/add HTTP/1.1
# content-type: application/json
#
POST http://localhost:3000/device/add HTTP/1.1
#
content-type: application/json
# {
# "sn":"sn1111211212122"
# }
#
{
#
"sn":"sn1111211212122"
#
}
# POST http://localhost:3000/device/addInfo HTTP/1.1
# content-type: application/json
...
...
@@ -15,4 +15,17 @@ http://localhost:3000/device?pageIndex=1&pageSize=1&user=李四
# "mobile":"3800138000"
# }
# http://localhost:3000/sse/event
\ No newline at end of file
# http://localhost:3000/sse/event
POST http://localhost:3000/broadcast/message HTTP/1.1
content-type: application/json
{
"event":"private",
"employeeId":"0.35481605237824265",
"data":{
"message":"hello limin"
}
}
\ No newline at end of file
yarn.lock
View file @
83be0cc
...
...
@@ -8607,13 +8607,20 @@ rxjs@6.6.3:
dependencies:
tslib "^1.9.0"
rxjs@6.6.7, rxjs@^6.0.0, rxjs@^6.
5.4, rxjs@^6.
6.0:
rxjs@6.6.7, rxjs@^6.0.0, rxjs@^6.6.0:
version "6.6.7"
resolved "https://registry.npmmirror.com/rxjs/download/rxjs-6.6.7.tgz?cache=0&sync_timestamp=1621619504812&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Frxjs%2Fdownload%2Frxjs-6.6.7.tgz#90ac018acabf491bf65044235d5863c4dab804c9"
integrity sha1-kKwBisq/SRv2UEQjXVhjxNq4BMk=
dependencies:
tslib "^1.9.0"
rxjs@^7.8.1:
version "7.8.1"
resolved "https://registry.npmmirror.com/rxjs/-/rxjs-7.8.1.tgz#6f6f3d99ea8044291efd92e7c7fcf562c4057543"
integrity sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==
dependencies:
tslib "^2.1.0"
safe-array-concat@^1.1.2:
version "1.1.2"
resolved "https://registry.npmmirror.com/safe-array-concat/-/safe-array-concat-1.1.2.tgz#81d77ee0c4e8b863635227c721278dd524c20edb"
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment