Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Implement WebSocket functionality using Gorilla WebSocket library for real-time communication #27

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions backend/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"regexp"

"log"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"

Expand Down Expand Up @@ -189,8 +190,12 @@ func server() {
}

func main(){
// server();
StartWebSocketServer();
// Initialize the WebSocket hub
hub := NewChatHub()
go hub.Start()

// WebSocket route for handling connections
router.GET("/ws", WebSocketHandler(hub))
}

func helloWorld(ctx *gin.Context){
Expand Down
92 changes: 92 additions & 0 deletions backend/cmd/server/webscoket.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
"github.com/gin-gonic/gin"
)

// WebSocket upgrader to handle the WebSocket connection
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
// Allow all origins
return true
},
}

// ChatHub stores active WebSocket connections
type ChatHub struct {
clients map[*websocket.Conn]bool
broadcast chan []byte
register chan *websocket.Conn
unregister chan *websocket.Conn
}

// NewChatHub creates a new ChatHub instance
func NewChatHub() *ChatHub {
return &ChatHub{
clients: make(map[*websocket.Conn]bool),
broadcast: make(chan []byte),
register: make(chan *websocket.Conn),
unregister: make(chan *websocket.Conn),
}
}

// Start the hub to listen for events (new connections, messages, etc.)
func (hub *ChatHub) Start() {
for {
select {
case conn := <-hub.register:
hub.clients[conn] = true
fmt.Println("New client connected")

case conn := <-hub.unregister:
if _, ok := hub.clients[conn]; ok {
delete(hub.clients, conn)
conn.Close()
fmt.Println("Client disconnected")
}

case message := <-hub.broadcast:
for client := range hub.clients {
err := client.WriteMessage(websocket.TextMessage, message)
if err != nil {
fmt.Println("Error broadcasting message:", err)
client.Close()
delete(hub.clients, client)
}
}
}
}
}

// WebSocketHandler handles WebSocket connections and message reception
func WebSocketHandler(hub *ChatHub) gin.HandlerFunc {
return func(c *gin.Context) {
// Upgrade the HTTP connection to a WebSocket connection
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println("WebSocket upgrade failed:", err)
return
}

// Register the new connection in the hub
hub.register <- conn
defer func() {
hub.unregister <- conn
}()

// Handle incoming messages from the WebSocket client
for {
_, message, err := conn.ReadMessage()
if err != nil {
fmt.Println("Error reading message:", err)
break
}
// Broadcast the received message to all connected clients
hub.broadcast <- message
}
}
}