Is websocket "Send / Receive thread safe" (go to normal)?

When writing a websocket server in GO (in my case using the JSON codec), is it safe to have two different Go procedures to handle sending and receiving data over the same connection?

Since websocket.JSON.Receive pauses and waits for data to be received, I thought that a separate Go procedure for processing data sending would be a working solution if simultaneous sending / receiving is not possible in the same connection.

So, a working example below is bad practice?

 package main import ( "fmt" "net/http" "code.google.com/p/go.net/websocket" ) const queueSize = 20 type Input struct { Cmd string } type Output struct { Cmd string } func Handler(ws *websocket.Conn) { msgWrite := make(chan *Output, queueSize) var in Input go writeHandler(ws, msgWrite) for { err := websocket.JSON.Receive(ws, &in) if err != nil { fmt.Println(err) break } else { msgWrite <- &Output{Cmd: "Thanks for your message: " + in.Cmd} } } } func writeHandler(ws *websocket.Conn, out chan *Output) { var d *Output for { select { case d = <-out: if err := websocket.JSON.Send(ws, &d); err != nil { fmt.Println(err.Error()) } else { fmt.Println("> ", d.Cmd) } } } } func main() { http.Handle("/echo", websocket.Handler(Handler)); err := http.ListenAndServe(":1235", nil); if err != nil { panic("ListenAndServe: " + err.Error()) } fmt.Println("Server running") } 
+6
source share
2 answers

Yes, you can simultaneously call, receive and close the connection to the website, as you can with all net.Conn in Go. Brief excerpt from official documents:

Several goroutines can simultaneously refer to methods on Conn.

In addition, the websocket package also introduces some codecs for sending / recording messages or JSON data, which can take several frames atomically. If you look at the source, you will see that the method of sending and receiving a Codec type will contain either read or write lock.

+9
source

Quote from http://www.gorillatoolkit.org/pkg/websocket

Concurrency

Connections support one simultaneous reader and one parallel writer.

Applications are responsible for ensuring that no more than one goroutine calls writing methods (NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, SetCompressionLevel) at the same time, and that no more than one goroutine calls reading methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPongHandler, SetPongHandler, .

The Close and WriteControl methods can be called simultaneously with all other methods.

0
source

Source: https://habr.com/ru/post/917821/


All Articles