Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang one to one chat

Tags:

websocket

go

chat

I want make one to one chat on golang and I find this simple script with websocket it work really well and it is one room with how much users inside you want. But I want convert it to one to one like facebook this is script if someone can help because I dont know am I need use more connections or filter users.

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)
            }
        }
    }
}

am I need change this part

clients[ws] = true
like image 989
bajro91 Avatar asked Sep 25 '17 22:09

bajro91


1 Answers

You would need to do few things:

  1. Get rid of broadcast channel
  2. Somehow pass & get from request to which client your user want to connect. Some room number/name, secret code? For example an URL parameter /ws?chat=abc. You probably would need to maintain a map[chatid][]*websocket.Conn
  3. Match 2 (or more) clients.
  4. Maintain a map, probably of type map[*websocket.Conn]*websocket.Conn
  5. On receiving a message from a client lookup the map and send the message to the matching client. In similar way as in handleMessages() but just once.

Please note StackOverflow is not a place to ask to write code for you.

like image 187
Alexander Trakhimenok Avatar answered Sep 19 '22 07:09

Alexander Trakhimenok