Web Socket
In the modern development sending the real time and fast data is most common use and how this will be helpful using the web socket.
A WebSocket is a communication protocol that provides full-duplex, persistent communication between a client (typically a web browser) and a server over a single, long-lived TCP connection.
WebSocket allows real-time data exchange between a client and a server without the need to repeatedly make HTTP requests.
Key Features:
Full-duplex communication: Both client and server can send messages independently at any time.
Low latency: Messages are sent instantly without the overhead of repeatedly opening and closing HTTP connections.
Persistent connection: Once opened, the connection remains active until explicitly closed.
Lightweight: Less overhead compared to HTTP for each message.
How the Web socket will make the connections: -
So they will follw the 3 way handshake connection 1. first the client will send the http request to the web socket and then they return the response 101 (means that switching protocol). and then the web socket connection will establish

By using the web socket we make the pool to manage the concurrent user. in the Concurrent user mapping. In that we make establish the user tennal with the specific pool so that i the concurreny and the dynamic data handling will be manage.
Http Streaming : - The Http streaming is the traditional method in the http streaming the data is continuously flush from the buffer so that we don't need to make the request for data. In Http request we send the request to the server than response us. HTTP Streaming and Web Socket
Feature
HTTP Streaming
WebSockets
Connection Type
Request/Response (one-way), Persistent
Full-duplex (two-way)
Direction of Communication
Server-to-client (client initiates only)
Bi-directional (client and server can push)
Use Case
Server-Sent Events, video streaming
Real-time chat, games, stock tickers
Overhead
More overhead (HTTP headers per request)
Less overhead after initial handshake
Latency
Higher (HTTP request/response cycle)
Low latency (messages sent instantly)
Protocol
HTTP/1.1, HTTP/2
Custom protocol over a single TCP connection
Web Socket Implementation in Golang
101 Switching protocol used for converting the Http request to web socket request.
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
In this code the upgrader is used for Converting the HTTP request to web socket connection. IN this code the Check Origin is used for Allowing the All kind domain request.
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin")
return origin == "http://localhost:5173"
},
}
In this code we only allowing to accept request from port 5173.
Using Go routine: - Using go routine is helpful for the managing the multiple thread and concurrent user at the same time. Also In the single go thread we can make the multiple web socket.
Code
Now here the code that will explain the working of the web socket and user memory management by the separate.
package main
import (
"context"
"log"
"net/http"
"strings"
"sync"
"github.com/gorilla/websocket"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var webConn sync.Map
type userSession struct {
conn *websocket.Conn
messages []openai.ChatCompletionMessageParamUnion
mutex sync.Mutex
}
func chatUser(session *userSession, prompt string) string {
client := openai.NewClient(
option.WithAPIKey("OPENAI_API_KEY"),
)
session.mutex.Lock()
defer session.mutex.Unlock()
session.messages = append(session.messages, openai.UserMessage(prompt))
resp, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
Model: openai.ChatModelChatgpt4oLatest,
Messages: session.messages,
})
if err != nil {
log.Println("OpenAI Chat Error:", err)
return "Sorry, I had an issue processing that."
}
content := strings.TrimSpace(resp.Choices[0].Message.Content)
session.messages = append(session.messages, openai.AssistantMessage(content))
return content
}
func handleClient(userID string, conn *websocket.Conn) {
defer conn.Close()
defer webConn.Delete(userID)
log.Printf("User %s connected", userID)
session := &userSession{
conn: conn,
messages: []openai.ChatCompletionMessageParamUnion{openai.SystemMessage("You are a sweet AI Girlfriend.")},
}
webConn.Store(userID, session)
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Printf("User %s disconnected: %v", userID, err)
return
}
go func(message string) {
response := chatUser(session, message)
err := conn.WriteMessage(websocket.TextMessage, []byte(response))
if err != nil {
log.Printf("Failed to send to %s: %v", userID, err)
}
}(string(msg))
}
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
userID := r.URL.Query().Get("uid")
if userID == "" {
http.Error(w, "Missing USER ID", http.StatusBadRequest)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("WebSocket upgrade error: %v", err)
return
}
go handleClient(userID, conn)
}
func main() {
http.HandleFunc("/ws", wsHandler)
log.Println("Server started on :8001")
err := http.ListenAndServe(":8001", nil)
if err != nil {
log.Fatalf("ListenAndServe error: %v", err)
}
}
Last updated