introduction
In Internet applications, real-time communication is a very important feature. WebSocket is a TCP-based protocol that allows two-way communication between clients and servers. Golang is a high-performance programming language that provides native support for WebSocket, making it very easy to create WebSocket sessions in Golang. This article will explain how to use Golang to create a separate WebSocket session for real-time communication.
Introduction to WebSocket
WebSocket is a protocol for full duplex communication on a single TCP connection. It is different from the traditional HTTP protocol, which is a stateless protocol that requires a new connection to be established for each request. WebSocket establishes a persistent connection between the client and the server, which can achieve real-time two-way communication.
The handshake of the WebSocket protocol is completed through HTTP requests. After the handshake, the connection between the client and the server will remain open, and any data can be sent and received. WebSocket uses an event-like mechanism whereby when new messages arrive, the server can actively push them to the client without the need to actively send requests.
WebSocket Support in Golang
Golang providesnet/http
Packages to handle HTTP requests and responses, and also providegorilla/websocket
Library to implement support of the WebSocket protocol.gorilla/websocket
is a very popular third-party library that provides advanced encapsulation of the WebSocket protocol, making it easier to create WebSocket sessions in Golang.
Before we start, we need to installgorilla/websocket
Library. You can use the following command to install:
go get /gorilla/websocket
After the installation is complete, we can start creating a WebSocket session.
Create a WebSocket Server
First, we need to create a WebSocket server that receives connection requests from the client and handles WebSocket sessions. Here is a simple WebSocket server example:
package main import ( "log" "net/http" "/gorilla/websocket" ) // Create an upgrader object to upgrade HTTP connection to WebSocket connectionvar upgrader = { ReadBufferSize: 1024, WriteBufferSize: 1024, } func main() { ("/ws", handleWebSocket) ((":8080", nil)) } func handleWebSocket(w , r *) { // Upgrade HTTP connection to WebSocket connection conn, err := (w, r, nil) if err != nil { ("Upgrade failed:", err) return } defer () // Handle WebSocket sessions for { // Read the message sent by the client messageType, message, err := () if err != nil { ("Read message failed:", err) break } // Process the messages sent by the client ("Received message: %s", message) // Reply to client messages err = (messageType, message) if err != nil { ("Write message failed:", err) break } } }
In the example above, we first create aupgrader
Object, which is used to upgrade an HTTP connection to a WebSocket connection. Then, we defined ahandleWebSocket
Function, used to handle WebSocket sessions. In this function, we first upgrade the HTTP connection to a WebSocket connection, and then enter an infinite loop, constantly reading the messages sent by the client and replying to the client with the same message.
Finally, we useThe function will
/ws
Path map tohandleWebSocket
Function, and then callFunction to start the WebSocket server.
Create a WebSocket Client
Next, we need to create a WebSocket client that sends WebSocket requests to the server and processes the messages pushed by the server. Here is a simple WebSocket client example:
package main import ( "log" "os" "os/signal" "time" "/gorilla/websocket" ) func main() { // Create a dialer object to establish a WebSocket connection dialer := { HandshakeTimeout: 10 * , } // Create a WebSocket connection conn, _, err := ("ws://localhost:8080/ws", nil) if err != nil { ("Dial failed:", err) } defer () // Start a goroutine to receive messages pushed by the server go func() { for { _, message, err := () if err != nil { ("Read message failed:", err) break } ("Received message: %s", message) } }() // Send a message to the server message := []byte("Hello, WebSocket!") err = (, message) if err != nil { ("Write message failed:", err) return } // Wait for the user to press Ctrl+C to terminate the program interrupt := make(chan , 1) (interrupt, ) <-interrupt }
In the example above, we first create adialer
Object, which is used to establish WebSocket connections. Then, we useThe function establishes a WebSocket connection and specifies the address of the server as
ws://localhost:8080/ws
. Then, we useThe function sends a message to the server and uses a goroutine to receive messages pushed by the server.
Finally, we useFunctions to register a signal listener. When the user presses Ctrl+C, the program will receive an interrupt signal and the program will exit.
Create a separate session
In practical applications, we may need to create a separate session for each client in order to manage and track the client's status. In Golang, this can be done by creating a separate goroutine for each WebSocket connection. Here is an example:
package main import ( "log" "net/http" "/gorilla/websocket" ) var upgrader = { ReadBufferSize: 1024, WriteBufferSize: 1024, } func main() { ("/ws", handleWebSocket) ((":8080", nil)) } func handleWebSocket(w , r *) { conn, err := (w, r, nil) if err != nil { ("Upgrade failed:", err) return } defer () // Create a separate session session := NewSession() // Handle session (conn) } type Session struct { conn * } func NewSession() *Session { return &Session{} } func (s *Session) Handle(conn *) { = conn go () go () } func (s *Session) readLoop() { for { messageType, message, err := () if err != nil { ("Read message failed:", err) break } ("Received message: %s", message) } } func (s *Session) writeLoop() { for { select { // Get the message from the message queue and send it to the client case message := <-: err := (, message) if err != nil { ("Write message failed:", err) } } } }
In the above example, we first define aSession
Structure, which contains a WebSocket connection. Then, we created aNewSession
Function, used to create a new session object. There are two important methods for session objects:Handle
Methods
Scene
Golang's WebSocket can be used to create separate sessions and is suitable for many scenarios. The following is an introduction to a usage scenario:
Scene: Online Chat Room
In an online chat room, users can communicate with other users in real time through WebSocket. Each user can create a separate session, conduct private chats with other users, or send messages in groups.
Use scenario description:
- The user enters the chat room and enters the nickname and chat content on the front-end page.
- The front-end page establishes a connection with the back-end Golang server through WebSocket.
- The backend server uses Golang's WebSocket package to handle client connection requests.
- When a user sends a message, the front-end page sends the message to the back-end server via WebSocket.
- After receiving the message, the backend server broadcasts it to all online users, or only sends it to specific users as needed.
- Each connected client can receive messages sent by other users and display them on the front-end page.
In this scenario, Golang's WebSocket implements real-time communication between users and maintains the independence of each user's session. It can handle concurrent connections, allowing multiple users to chat at the same time without interfering with each other.
It is worth noting that Golang's WebSocket can also ensure the security of chat rooms by adding the necessary security and authentication mechanisms. For example, you can encrypt the connection using SSL/TLS, or use a token for user authentication. These security measures can ensure that users’ chat content and personal information are protected.
Summarize
This is the end of this article about creating a separate session with Go WebSocket. For more related content about creating a separate session with Go WebSocket, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!