SoFunction
Updated on 2025-03-05

A brief analysis of the use of Golang websocket protocol

The main differences between WebSocket and HTTP protocols

Differences between HTTP and WebSocket protocols HTTP is one-way, while WebSocket is two-way.

In communication between the client and the server, each HTTP request from the client establishes a new connection and closes after a response is received from the server, while the WebSocket connection is established only once and is reused before the server or client terminates the connection.

The timeout time for an idle connection to HTTP is 60 seconds. Can be used for calls with very short response times.

The timeout for a WebSocket idle connection is 3600 seconds (1 hour), which can be applied to calls with response time longer than 60 seconds, with a maximum number of connections of 250.

WebSocket Server

First, create an HTTP server. In this server, create a function handleWebSocket to handle the WebSocket connection.

In fact, it is to enable an http server.

func HandleWebSocket(w , r *) {
}
func main() {
	("/ws", HandleWebSocket)
	(":8080", nil)
}

Then in this function, use the gorilla/websocket package to handle the WebSocket connection.

1. Create upgrade variable.

The handshake process of establishing connections in the websocket protocol is that the head of the http protocol adds the upgrade field (upgrade:websocket).

First, import the "/gorilla/websocket" package

var upgrade = {
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *) bool {
		return true
	},
}

2. Upgrade http connection to websocket connection and handle websocket connection

Add the http connection header to the upgrade field and become the websocket protocol.

func HandleHome(w , r *) {
	//Upgrade to websocket	conn, err := (w, r, nil)
	if err != nil {
		(err)
	}
	//websocket read and write logic	for {
		messageType, p, err := ()
		if err != nil {
			(err)
			return
		}
		("receive:", string(p))
		(messageType, []byte("hello, i am server"))
	}
}

WebSocket Client

The client is mainly used to test whether the websocket server works correctly. The following two websocket servers are provided.

html+js implementation

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Test</title>
</head>
<body>
    <script>
        var ws = new WebSocket("ws://localhost:8080/ws");
         = function() {
            ("WebSocket connection opened.");
	("Hi From the Client!")
        };
         = function(event) {
            ("Received message: " + );
        };
         = function() {
            ("WebSocket connection closed.");
        };
         = function(event) {
            ("WebSocket error: " + );
        };
    </script>
</body>
</html>

Implementation with golang websocket package

func WebSocketClient() {
	conn, _, err := ("ws://127.0.0.1:8080/ws", nil)
	if err != nil {
		panic(err)
	}
	defer ()
	for {
		()
		(, []byte("hi i am client"))
		_, p, err := ()
		if err != nil {
			(err)
		}
		println("client recv:", string(p))
	}
}

This is the end of this article about the use of the Golang websocket protocol. For more related Go websocket content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!