What are WebSockets?
sobes.tech AI
Answer from AI
WebSockets is a network communication protocol that provides a bidirectional, persistent, and full-duplex connection between a client (usually a browser) and a server over a single TCP socket.
Unlike traditional HTTP, where the client sends a request and the server responds and then the connection is closed, WebSocket establishes a persistent connection, allowing both parties to send data at any time without needing to re-establish the connection.
This is especially useful for real-time applications such as chats, online games, trading platforms, etc.
In Go, the gorilla/websocket library is often used for working with WebSocket. Here's an example of a simple server:
package main
import (
"net/http"
"github.com/gorilla/websocket"
"log"
)
var upgrader = websocket.Upgrader{}
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("Upgrade error:", err)
return
}
defer conn.Close()
for {
messageType, message, err := conn.ReadMessage()
if err != nil {
log.Println("Read error:", err)
break
}
log.Printf("Received: %s", message)
err = conn.WriteMessage(messageType, message)
if err != nil {
log.Println("Write error:", err)
break
}
}
}
func main() {
http.HandleFunc("/ws", wsHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
This server accepts WebSocket connections and sends back the received messages as an echo.