refactor: improve ws code

This commit is contained in:
草鞋没号 2021-11-09 08:59:37 +08:00
parent d3567065e8
commit a96991ac38
4 changed files with 55 additions and 45 deletions

View File

@ -1,27 +1,33 @@
/** /**
* Ws server side
* Hot reload from preload script during development * Hot reload from preload script during development
*/ */
import WebSocket from 'ws' import WebSocket from 'ws'
import chalk from 'chalk' import chalk from 'chalk'
import pkg from '../package.json' 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 = '[ws.ts]'
const { TAG } = options
export function createWsServer(options: CreateWsServerOptions = {}): WssServer {
const port = pkg.env.PORT_WS 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 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}`)) console.log(TAG, 'Wss run at - ' + chalk.yellow(`ws://${host}:${port}`))
wss.on('connection', ws => { wss.on('connection', ws => {
console.log(TAG, chalk.yellow(`wss.on('connection')`)) console.log(TAG, chalk.yellow(`wss.on('connection')`))
wssObj.instance = ws wssInstance.instance = ws
ws.on('message', message => { ws.on('message', message => {
console.log(TAG, `ws.on('message'):`, message.toString()) console.log(TAG, `ws.on('message'):`, message.toString())
}) })
@ -32,10 +38,10 @@ export function createWsServer(options: CreateWsServerOptions) {
wss.on('close', () => { wss.on('close', () => {
console.log(TAG, chalk.gray(`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 }) { export function formatWsSendData(json: { cmd: string, data?: any }) {

View File

@ -1,6 +1,7 @@
import fs from 'fs' import fs from 'fs'
import { contextBridge, ipcRenderer } from 'electron' import { contextBridge, ipcRenderer } from 'electron'
import { domReady, injectWsCode } from './utils' import { domReady } from './utils'
import { injectWsCode } from './ws'
import { useLoading } from './loading' import { useLoading } from './loading'
const isDev = process.env.NODE_ENV === 'development' const isDev = process.env.NODE_ENV === 'development'
@ -9,7 +10,7 @@ const { removeLoading, appendLoading } = useLoading()
domReady().then(() => { domReady().then(() => {
appendLoading() appendLoading()
isDev && injectWsCode({ isDev && injectWsCode({
host: '127.0.0.1', host: process.env.HOST, // '127.0.0.1'
port: process.env.PORT_WS as string, // process.env.npm_package_env_PORT_WS port: process.env.PORT_WS as string, // process.env.npm_package_env_PORT_WS
}) })
}) })

View File

@ -13,37 +13,3 @@ export function domReady(condition: DocumentReadyState[] = ['complete', 'interac
} }
}) })
} }
/** Inject ws related code */
export function injectWsCode(options: {
host: string
port: string | number
}) {
const oScript = document.createElement('script')
oScript.id = 'ws-preload-hot-reload'
oScript.innerHTML = `
${__ws_hot_reload_for_preload.toString()}
${__ws_hot_reload_for_preload.name}(${JSON.stringify(options)})
`
document.body.appendChild(oScript)
}
function __ws_hot_reload_for_preload(options: { host: string; port: string | number }) {
const ws = new WebSocket(`ws://${options.host}:${options.port}`)
ws.onmessage = function (ev) {
try {
console.log('[preload] ws.onmessage:', ev.data)
const data = JSON.parse(ev.data) // { "cmd": "string", data: "string|number" }
if (data.cmd === 'reload') {
setTimeout(() => window.location.reload(), 999)
}
} catch (error) {
console.warn(`ws.onmessage should be accept "JSON.string" formatted string.`)
console.error(error)
}
}
}

37
src/preload/ws.ts Normal file
View File

@ -0,0 +1,37 @@
/**
* Ws client side
*/
/** Inject ws client-side code */
export function injectWsCode(options: {
host: string
port: string | number
}) {
const oScript = document.createElement('script')
oScript.id = 'ws-preload-hot-reload'
oScript.innerHTML = `
${__ws_hot_reload_for_preload.toString()}
${__ws_hot_reload_for_preload.name}(${JSON.stringify(options)})
`
document.body.appendChild(oScript)
}
function __ws_hot_reload_for_preload(options: { host: string; port: string | number }) {
const ws = new WebSocket(`ws://${options.host}:${options.port}`)
ws.onmessage = function (ev) {
try {
console.log('[preload] ws.onmessage:', ev.data)
const data = JSON.parse(ev.data) // { "cmd": "string", data: "string|number" }
if (data.cmd === 'reload') {
setTimeout(() => window.location.reload(), 999)
}
} catch (error) {
console.warn(`ws.onmessage should be accept "JSON.string" formatted string.`)
console.error(error)
}
}
}