我想在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 

2017-09-25 bajro91

+0

你能解决这个问题吗?我也在做同样的事情,需要一些建议 –