This is a creation in Article, where the information may have evolved or changed.
Design ideas: Each websocket allows the connection is time-limited, after timeout, the server will automatically disconnect, then the long connection on the service side after the disconnection information sent by the client to detect the disconnection information to initiate a connection request, and then through the handshake information to ensure that the client is connected with the servers.
Design structure:
Type longsocket struct {Ws *websocket. Connwritech Chan []bytereadch Chan []byteshakehand boolurl stringprotocol stringorigin Stringbuffersize intstatus intmu sync. Mutex}
The long connection actively sends a message to the connecting party via the ' Writech ' channel, reading the information in the connection through the ' READCH ' channel, setting ' Shakehand ' to determine whether to send the handshake information, status to identify the connection status.
Through the Writeloop to send handshake information, while listening to the ' Writech ' channel, forward the message in the channel.
Call Func with a gorouting, it'll send shake hands message to service to make sure-is ok//if-want to send Mes Sage call func ' Write ', and the case Writech would be Vaildfunc (L *longsocket) Writeloop () {defer func () {if err: = Recove R (); Err! = Nil {//fmt. Println ("Writeloop", Err)}} () for {errcount: = 0if l.status! = status_connect {break}select {case <-time. After (time. Second * time. Duration (shake_hands_frequency)): If L.shakehand {_, Err: = L.ws.write ([]byte (shake_hands_msg)) if err! = Nil {errcount++ }}case msg: = <-l.writech:_, err: = L.ws.write (msg) if err! = nil {errcount++}}if ErrCount! = 0 {break}}l.close ()}
The message is received via Readloop and forwarded to the ' READCH ' channel.
Read Message form socket and write them to Readchfunc (L *longsocket) Readloop () {defer func () {if err: = Recover (); Err ! = Nil {//fmt. Println ("Readloop", Err)}} () for {if l.status! = status_connect {break}buf: = make ([]byte, L.buffersize) n, err: = L.ws.read (BUF) If err! = Nil {break}if n > 0 {l.readch <-buf[0:n]}}l.close ()}
The message can then be forwarded through the Read function to a shape such as
Typedealmsg func ([] Byte, * Longsocket)error
function to do the corresponding message processing, of course, you can also send the corresponding processing message through the Longsocket parameter.
Source has been uploaded githup as follows, including demo for reference.
Https://github.com/qianlnk/longsocket