What is a WebSocket?
WebSocket is a protocol that allows for persistent, bidirectional communication between a client and server. Once a WebSocket connection is established, data can be sent back and forth in real time, making it perfect for applications that require continuous data exchange, like chat applications, gaming, or real-time updates.
Setting Up Go for WebSocket Development
To start creating a WebSocket server in Go, make sure you have Go installed. You can download it from the official site. Once Go is installed, you can setup your project and dependencies.
mkdir websocket-example
cd websocket-example
Installing the Gorilla WebSocket Package
The Gorilla WebSocket package is a popular library for managing WebSocket connections in Go. Install this package using the following:
go get -u github.com/gorilla/websocket
Creating a Basic WebSocket Server
Now, let’s create a simple WebSocket server using the Gorilla WebSocket package. First, create a new Go file:
touch main.go
Open main.go in your preferred editor and enter the following code:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Error upgrading connection:", err)
return
}
defer conn.Close()
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
fmt.Println("Error reading message:", err)
return
}
fmt.Printf("Received message: %s\n", p)
if err := conn.WriteMessage(messageType, p); err != nil {
fmt.Println("Error writing message:", err)
return
}
}
}
func main() {
http.HandleFunc("/ws", handleConnections)
port := "8080"
fmt.Printf("Starting server on http://localhost:%s\n", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
fmt.Println("Error starting server:", err)
}
}
Running Your WebSocket Server
To run your server, open a terminal, navigate to your project directory, and execute:
go run main.go
Your WebSocket server should now be running on http://localhost:8080.
Testing Your WebSocket Server
You can test your WebSocket server using a simple HTML client. Create a new file named index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Client</h1>
<textarea id="messages" cols="30" rows="10" disabled></textarea>
<button onclick="connectWebSocket()">Connect</button>
<input id="messageInput" type="text" placeholder="Enter your message"/>
<button onclick="sendMessage()">Send</button>
<script>
const messages = document.getElementById('messages');
const messageInput = document.getElementById('messageInput');
let socket;
function connectWebSocket() {
socket = new WebSocket('ws://localhost:8080/ws');
socket.onopen = function() {
messages.value += 'Connected to WebSocket server\n';
};
socket.onmessage = function(event) {
messages.value += 'Received: ' + event.data + '\n';
};
}
function sendMessage() {
const message = messageInput.value;
socket.send(message);
messages.value += 'Sent: ' + message + '\n';
messageInput.value = '';
}
</script>
</body>
</html>
Open index.html in a browser and click Connect. You can now send messages to your WebSocket server and receive back what you send, demonstrating a simple echo server.