2017-09-25 149 views
3

我想在golang上進行一對一的聊天,我發現這個帶有websocket的簡單腳本工作得很好,它是一個房間,裏面有多少用戶想要。但我想將它轉換爲像facebook一樣一個這是腳本如果有人可以幫助,因爲我不知道我需要使用更多的連接或篩選用戶。Golang一對一聊天

package main 

import (
    "log" 
    "net/http" 

    "github.com/gorilla/websocket" 
) 

var clients = make(map[*websocket.Conn]bool) // connected clients 
var broadcast = make(chan Message)   // broadcast channel 

// Configure the upgrader 
var upgrader = websocket.Upgrader{ 
    CheckOrigin: func(r *http.Request) bool { 
     return true 
    }, 
} 

// Define our message object 
type Message struct { 
    Email string `json:"email"` 
    Username string `json:"username"` 
    Message string `json:"message"` 
    Created string `json:"created"` 
} 

func main() { 
    // Create a simple file server 
    fs := http.FileServer(http.Dir("public")) 
    http.Handle("/", fs) 

    // Configure websocket route 
    http.HandleFunc("/ws", handleConnections) 

    // Start listening for incoming chat messages 
    go handleMessages() 

    // Start the server on localhost port 8000 and log any errors 
    log.Println("http server started on :8090") 
    err := http.ListenAndServe(":8090", nil) 
    if err != nil { 
     log.Fatal("ListenAndServe: ", err) 
    } 
} 

func handleConnections(w http.ResponseWriter, r *http.Request) { 
    // Upgrade initial GET request to a websocket 
    ws, err := upgrader.Upgrade(w, r, nil) 
    if err != nil { 
     log.Fatal(err) 
    } 
    // Make sure we close the connection when the function returns 
    defer ws.Close() 

    // Register our new client 
    clients[ws] = true 

    for { 
     var msg Message 
     // Read in a new message as JSON and map it to a Message object 
     err := ws.ReadJSON(&msg) 
     if err != nil { 
      log.Printf("error: %v", err) 
      delete(clients, ws) 
      break 
     } 
     // Send the newly received message to the broadcast channel 
     broadcast <- msg 
    } 
} 

func handleMessages() { 
    for { 
     // Grab the next message from the broadcast channel 
     msg := <-broadcast 
     // Send it out to every client that is currently connected 
     for client := range clients { 
      err := client.WriteJSON(msg) 
      if err != nil { 
       log.Printf("error: %v", err) 
       client.Close() 
       delete(clients, client) 
      } 
     } 
    } 
} 

是我需要改變這一部分

clients[ws] = true 
+0

你能解決這個問題嗎?我也在做同樣的事情,需要一些建議 –

回答

4

你需要做幾件事情:

  1. 擺脫broadcast通道
  2. 某種方式傳遞&從請求得到它您的用戶想要連接的客戶端。一些房間號/名稱,密碼?例如URL參數/ws?chat=abc。您可能需要維護一個map[chatid][]*websocket.Conn
  3. 匹配2(或更多)客戶端。
  4. 維護地圖,可能類型爲map[*websocket.Conn]*websocket.Conn
  5. 在從客戶端接收到消息查找地圖並將消息發送到匹配的客戶端。與handleMessages()類似,但只是一次。

請注意StackOverflow不是要求爲您編寫代碼的地方。

相關問題