From cccbfc2e8ec5cead9e75f8cdfe03e7c224408e7a Mon Sep 17 00:00:00 2001 From: lakinduakash Date: Thu, 23 May 2019 03:05:20 +0530 Subject: [PATCH] Set nickname on clients --- websocket/client.go | 25 ++++++++++++++++++------- websocket/pool.go | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/websocket/client.go b/websocket/client.go index 2a536f5..9cf9a02 100644 --- a/websocket/client.go +++ b/websocket/client.go @@ -2,7 +2,6 @@ package websocket import ( "encoding/json" - "fmt" "github.com/gorilla/websocket" "log" ) @@ -20,9 +19,10 @@ type Message struct { } type MessageBody struct { - From string `json:"from"` - To string `json:"to"` - Message string `json:"message"` + From string `json:"from"` + To string `json:"to"` + Message string `json:"message"` + Nickname string `json:"nickname"` } func (c *Client) Read() { @@ -44,9 +44,20 @@ func (c *Client) Read() { log.Println(err) continue } - body.From = c.ID - message := Message{Type: 1, Body: body} + + var message Message + + if body.Nickname != "" { + c.Nickname = body.Nickname + body.From = c.ID + message = Message{Type: 4, Body: body} + } else { + body.From = c.ID + message = Message{Type: 1, Body: body} + } + c.Pool.Broadcast <- &message - fmt.Printf("Message Received: %+v\n", message) + + //fmt.Printf("Message Received: %+v\n", message) } } diff --git a/websocket/pool.go b/websocket/pool.go index 2f6307d..5b40335 100644 --- a/websocket/pool.go +++ b/websocket/pool.go @@ -48,6 +48,15 @@ func (pool *Pool) Start() { } } + + for _, client2 := range pool.Clients { + if err := client.Conn.WriteJSON(Message{Type: 2, Body: MessageBody{Message: client2.ID, Nickname: client2.Nickname}}); err != nil { + log.Fatal("Error on write") + continue + } + + } + break case client := <-pool.Unregister: delete(pool.Clients, client.ID) @@ -71,6 +80,16 @@ func (pool *Pool) Start() { fmt.Println(err) } } + } else if message.Type == 4 { + + for _, client := range pool.Clients { + + if err := client.Conn.WriteJSON(*message); err != nil { + fmt.Println(err) + continue + } + + } } else { //fmt.Println("Sending message to all clients in Pool") for _, client := range pool.Clients {