WebSockets are a powerful tool for enabling real-time updates in web applications. They provide a full-duplex communication channel over a single TCP connection, which allows for instant data exchange between a client and server. This is particularly useful for applications like chat apps, live notifications, and collaborative tools.
Below is a basic example of how to set up a WebSocket server in Go and connect to it from a web client:
// Go WebSocket server setup
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
func handler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Error during connection upgrade:", err)
return
}
defer conn.Close()
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
fmt.Println("Error reading message:", err)
break
}
fmt.Println("Received:", string(msg))
if err := conn.WriteMessage(msgType, msg); err != nil {
fmt.Println("Error writing message:", err)
break
}
}
}
func main() {
http.HandleFunc("/ws", handler)
http.ListenAndServe(":8080", nil)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?