Advertisement
mamanegoryu1

Untitled

Dec 17th, 2018
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.36 KB | None | 0 0
  1. func handleConnections(conn *websocket.Conn) {
  2.     // Make sure we close the connection when the function returns
  3.     defer conn.Close()
  4.  
  5.     userName, err := getUsernameFromConn(conn)
  6.     if err != nil {
  7.         log.Fatal(err)
  8.         return
  9.     }
  10.  
  11.     fmt.Println("Hello *** user ", userName)
  12.     salutionNewUser(userName, broadcast)
  13.  
  14.     // Register our new client
  15.     addConn(conn, userName)
  16.  
  17.     // TODO: fix lock
  18.     // if isItNewUser(conn, userName) {
  19.     //  fmt.Println("Hello *** user ", userName)
  20.     //  salutionNewUser(userName, broadcast)
  21.     // }
  22.  
  23.     go listeningMsgs(conn, broadcast)
  24. }
  25.  
  26. func listeningMsgs(conn *websocket.Conn, broadcastCh chan Message) {
  27.     for {
  28.         var msg Message
  29.         // Read in a new message as JSON and map it to a Message object
  30.         // err := ws.ReadJSON(&msg)     // gorilla
  31.         err := websocket.JSON.Receive(conn, &msg)
  32.         if err != nil {
  33.             log.Printf("error: %v", err)
  34.             removeConn(conn, userName)
  35.             return
  36.         }
  37.  
  38.         storedUserName, err := getUsernameFromConn(conn)
  39.         if storedUserName != msg.Username {
  40.             log.Fatal("Warning: stored-username and message-author mismatch. Connection will be refused.")
  41.             removeConn(conn, userName)
  42.             return
  43.         }
  44.  
  45.         // Add connectionId to the message
  46.         mu.Lock()
  47.         msg.ConnID = clients[conn]
  48.         mu.Unlock()
  49.  
  50.         // Send the newly received message to the broadcast channel
  51.         broadcastCh <- msg
  52.         fmt.Println(msg.Username, "> ", msg.Text)
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement