Golang一对一聊天

时间:2017-09-25 22:38:52

标签: go websocket chat

我想在golang上进行一对一的聊天,我发现这个简单的脚本与websocket它工作得非常好,它是一个房间,里面有你想要多少用户。但是我希望将它转换为一对一,就像facebook一样,这是脚本,如果有人可以提供帮助,因为我不知道我需要使用更多连接或过滤用户。

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

1 个答案:

答案 0 :(得分:5)

您需要做一些事情:

  1. 摆脱broadcast频道
  2. 以某种方式传递&amp;从请求获取您的用户想要连接的客户端。一些房间号/姓名,密码?例如,网址参数/ws?chat=abc。您可能需要维护map[chatid][]*websocket.Conn
  3. 匹配2(或更多)个客户。
  4. 维护地图,可能是map[*websocket.Conn]*websocket.Conn
  5. 类型
  6. 从客户端收到消息后,查找地图并将消息发送给匹配的客户端。与handleMessages()中的方式类似,只需一次。
  7. 请注意StackOverflow不是要求为您编写代码的地方。