mirror of
https://github.com/electron-vite/electron-vite-vue
synced 2025-08-24 21:51:27 +08:00
refactor: improve ws code
This commit is contained in:
@@ -1,27 +1,33 @@
|
||||
/**
|
||||
* Ws server side
|
||||
* Hot reload from preload script during development
|
||||
*/
|
||||
import WebSocket from 'ws'
|
||||
import chalk from 'chalk'
|
||||
import pkg from '../package.json'
|
||||
|
||||
export interface CreateWsServerOptions {
|
||||
TAG: string
|
||||
|
||||
export interface CreateWsServerOptions { }
|
||||
|
||||
export interface WssServer {
|
||||
wss: WebSocket.Server
|
||||
instance: WebSocket | null
|
||||
}
|
||||
|
||||
export function createWsServer(options: CreateWsServerOptions) {
|
||||
const { TAG } = options
|
||||
const TAG = '[ws.ts]'
|
||||
|
||||
export function createWsServer(options: CreateWsServerOptions = {}): WssServer {
|
||||
const port = pkg.env.PORT_WS
|
||||
const host = '127.0.0.1'
|
||||
const host = pkg.env.HOST // '127.0.0.1'
|
||||
const wss = new WebSocket.Server({ host, port })
|
||||
const wssObj: { wss: WebSocket.Server; instance: WebSocket | null } = { wss, instance: null }
|
||||
const wssInstance: WssServer = { wss, instance: null }
|
||||
|
||||
console.log(TAG, 'Wss run at - ' + chalk.yellow(`ws://${host}:${port}`))
|
||||
|
||||
wss.on('connection', ws => {
|
||||
console.log(TAG, chalk.yellow(`wss.on('connection')`))
|
||||
|
||||
wssObj.instance = ws
|
||||
wssInstance.instance = ws
|
||||
ws.on('message', message => {
|
||||
console.log(TAG, `ws.on('message'):`, message.toString())
|
||||
})
|
||||
@@ -32,10 +38,10 @@ export function createWsServer(options: CreateWsServerOptions) {
|
||||
wss.on('close', () => {
|
||||
console.log(TAG, chalk.gray(`wss.on('close')`))
|
||||
|
||||
wssObj.instance = null
|
||||
wssInstance.instance = null
|
||||
})
|
||||
|
||||
return wssObj
|
||||
return wssInstance
|
||||
}
|
||||
|
||||
export function formatWsSendData(json: { cmd: string, data?: any }) {
|
||||
|
Reference in New Issue
Block a user