添加websocet

master
wuzuowei 4 months ago
parent 0b1fd5a543
commit 0462ff6eed

@ -0,0 +1,163 @@
/**
* websocket
* author: frez02@126.com
* datetime: 2021-01-02
*/
export class WebSocketOption {
/**
* error
*/
autoStart: boolean = false
/**
*
*/
heart: string | false = false
/**
* WebSocket
*/
ws: string | null = null //ws://170.0.35.145:12781/rolling/wsnotify
/**
*
*/
type: "TCP" = "TCP"
//以下为回调函数
/**
* onopen
*/
onOpen?: Function
/**
* onmessage
*/
onMessage?: Function
/**
* onclose
*/
onClose?: Function
/**
* onerror
*/
onError?: Function
}
/**
* websocket
* author: frez02@126.com
* datetime: 2020-01-02
*/
export class WebSocketLoader {
protected server : WebSocket | null = null
protected option : WebSocketOption
protected disposed : boolean = false
protected paused : boolean = false
constructor(opts : WebSocketOption) {
this.option = opts
if(opts.autoStart) {
this.start()
}
}
/**
*
*/
start = () => {
this.restart()
}
/**
*
*/
restart = () => {
this.disposed = false
this.paused = false
this.connect()
}
/**
*
*/
pause = () => {
this.paused = true
}
/**
*
*/
resume = () => {
this.paused = false
}
protected connect = () => {
if(this.server == null){
this.server = new WebSocket(this.option.ws)
}
else if(this.server.readyState == 1){
this.server.close()
return
}
else if(this.server.readyState == 2){
return
}
else {
//0 - 尚未建立连接, 3 - 已经关闭或者已经不能打开
}
this.server.onclose = this.onClose
this.server.onopen = this.onOpen
this.server.onmessage = this.onMessage
this.server.onerror = this.onError
}
/**
*
*/
dispose = () => {
this.disposed = true
if(this.server == null){
return
}
if(this.server.readyState == 2) {
this.server.close()
}
}
/**
*
*/
isLive = () => {
return this.server == null ? false : (this.disposed == true ? false : this.server.readyState == 1)
}
protected onOpen = (e : any) => {
if(this.option.onOpen){
this.option.onOpen()
}
}
protected onClose = (e : any) => {
if(this.option.onClose){
this.option.onClose()
}
}
protected onMessage = (e : any) => {
if(this.option.onMessage){
this.option.onMessage(e.data)
}
}
protected onError = (e : any) => {
if(this.option.autoStart && this.disposed == false){
this.restart()
}
if(this.option.onError){
this.option.onError()
}
}
}
Loading…
Cancel
Save