After learning the basics of HTTP, I naturally came to the WebSocket protocol. Just two days ago, I practiced it again in order to compare the performance of WebSocket scripts in Java and Go. I feel that I can do it. I specially wrote an article to record it.
First, review the Java and Python test articles on Socket, WebSocket and Socket.IO.
- Development and test of socket interface
- client encapsulation based on WebSocket
- Client encapsulation based on Socket.IO
- Performance test practice of Socket interface fixed QPS
- Test practice of whiteboard dot matrix coordinate transmission interface based on Socket.IO
- Practice of asynchronous verification of Socket interface
- Multi user test practice of Socket.IO interface
- Socket.IO interface test script for Python
Let's share the development and testing of WebSocket interface with Go language.
rely on
This article uses the / net/websocket library and another / gorilla/websocket. I'll write an article and share it after I'm fully proficient. The biggest advantage of Go language library is that the same library can not only do interface development, but also send requests as clients.
WebSocket development
There is a big pit in this place. Many materials found on the Internet are outdated and actually can't run. The reason is that / net/websocket is relatively less used for server development. A wrong article was copied around the whole network, which greatly affected the experience of self-study Xiaobai.
Here, the function of the server is simple, and the function design is as follows: after receiving the client message, the returned message is the current time.
// Echo // @Description:WebSocket interface handle // @param ws func Echo(ws *websocket.Conn) { var err error for { var reply string if err = websocket.Message.Receive(ws, &reply); err != nil { fmt.Println("receive failed:", err) break } log.Printf("Received message:%s", reply) msg := string(time.Now().String()) websocket.Message.Send(ws, msg) } } // TestSer // @Description: create a WebSocket interface // @param t func TestSer(t *testing.T) { //Accept the routing address of websocket http.HandleFunc("/websocket", func(w http.ResponseWriter, req *http.Request) { s := websocket.Server{Handler: websocket.Handler(Echo)} s.ServeHTTP(w, req) }) if err := http.ListenAndServe(":1234", nil); err != nil { log.Fatal("ListenAndServe:", err) } }
The big hole here is that you need to convert the handle of WebSocket into the handle of HTTP. I personally understand that it is equivalent to the process of upgrader.
client
Here, you simply send a message to the server and print the message returned by the server. Because the logic of the server is simple, the client is also very simple. If you need to test WebSocket in combination with chan in the actual test, it is very easy to use.
// TestWebSocket // @Description: Test WebSocket script // @param t func TestWebSocket(t *testing.T) { url := "wss://wspri.coinall.ltd:8443/ws/v5/public" c, res, err := websocket.DefaultDialer.Dial(url, nil) if err != nil { log.Fatal("connection failed:", err) } log.Printf("response:%s", fmt.Sprint(res)) defer c.Close() done := make(chan struct{}) err = c.WriteMessage(websocket.TextMessage, []byte("Hello,I am FunTester")) if err != nil { fmt.Println(err) } go func() { defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Fatal(err) break } log.Printf("Received message: %s", message) } }() s := <-done fmt.Println(s) }
test
First start the server, and then start the client. The startup speed of Go language is much faster than that of Java, with obvious advantages.
I also wrote a Java test client:
package com.funtest.javatest; import com.funtester.frame.SourceCode; import com.funtester.socket.WebSocketFunClient; public class WebSocketT extends SourceCode { public static void main(String[] args) { WebSocketFunClient instance = WebSocketFunClient.getInstance("ws://localhost:1234/websocket"); instance.connect(); instance.send("Hello,I am FunTester - Java ,Have Fun ~ Tester !"); } }
Server log:
=== RUN TestSer 2021/11/09 18:03:20 Received message:Hello,I am FunTester - Go ,Have Fun ~ Tester ! 2021/11/09 18:05:49 Received message:Hello,I am FunTester - Java ,Have Fun ~ Tester !
Go client log:
=== RUN TestMn2 2021-11-09 18:03:20.570277 +0800 CST m=+11.854257683
Java client log:
INFO-> main Current user: oker,Working directory:/Users/oker/IdeaProjects/funtester/,System coding format:UTF-8,system Mac OS X edition:10.16 INFO-> main FunTester_0 Start connection... INFO-> WebSocketConnectReadThread-14 FunTester_0 Building socket connect... INFO-> WebSocketConnectReadThread-14 Handshake information key: Connection ,value: Upgrade INFO-> WebSocketConnectReadThread-14 Handshake information key: Sec-WebSocket-Accept ,value: mpWx5ntxvsNp75f8ubGZPmjSrn0= INFO-> WebSocketConnectReadThread-14 Handshake information key: Upgrade ,value: websocket INFO-> main FunTester_0 Connection succeeded! INFO-> WebSocketConnectReadThread-14 FunTester_0 received: 2021-11-09 18:05:49.374599 +0800 CST m=+43.517144103