WebSocket
Server and Client
Github Source: https://github.com/gogf/examples/tree/main/httpserver/websocket
Description
This example demonstrates how to implement WebSocket
communication using GoFrame
. The example includes both HTTP
and HTTPS
implementations with the following components:
WebSocket
server that handles both secure and non-secure connectionsWebSocket
client implementations for bothHTTP
andHTTPS
connections- Example of handling
WebSocket
message exchange
The implementation demonstrates:
- Basic
WebSocket
server setup - Secure
WebSocket
(WSS
) implementation - Client connection handling
- Message exchange between client and server
- Proper connection cleanup
Requirements
- Go
1.22
or higher - Git
- GoFrame
- Gorilla WebSocket
Structure
websocket/
├── http/
│ ├── client.go # HTTP WebSocket client
│ ├── server.go # HTTP WebSocket server
│ └── static/ # Static files directory
├── https/
│ ├── client.go # HTTPS WebSocket client
│ ├── server.go # HTTPS WebSocket server
│ ├── static/ # Static files directory
│ └── certs/ # SSL certificates
└── README.md
Features
WebSocket
server implementation- Secure
WebSocket
(WSS
) support - Client connection handling
- Message echo functionality
- Connection lifecycle management
- Origin checking (configurable)
- Error handling
Setup
-
Clone the repository:
git clone https://github.com/gogf/examples.git
cd examples/httpserver/websocket -
Install the dependencies:
go mod tidy
-
For
HTTPS/WSS
support, generate self-signed certificates (optional):mkdir -p https/certs
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout https/certs/server.key -out https/certs/server.crt
Usage
HTTP WebSocket
-
Start the server:
cd http
go run server.go -
Run the client:
cd http
go run client.go -
Access the demo page in browser:
Open
http://127.0.0.1:8000
in your browser to see theWebSocket
demo in action. The page provides a simple chat interface where you can send and receive messages in real-time.
HTTPS WebSocket
-
Start the secure server:
cd https
go run server.go -
Run the secure client:
cd https
go run client.go -
Access the demo page in browser: Open
https://127.0.0.1:8000
in your browser to see theWebSocket
demo in action. Note: Since we're using a self-signed certificate, your browser may show a security warning, which is normal.
Implementation Details
Server Features
WebSocket
upgrade handling- Message echo functionality
- Connection lifecycle management
- Configurable origin checking
- Error handling and logging
Client Features
- Connection establishment
- Message sending and receiving
TLS
configuration for secure connections- Clean connection closure
Notes
- The
WebSocket
server echoes back any message it receives - For
HTTPS
/WSS
, self-signed certificates are used in the example - In production, implement proper origin checking
- Handle connection closure properly to avoid resource leaks
More Information
For more details about WebSocket
implementation, please refer to: