This repository has been archived on 2023-07-05. You can view files and clone it, but cannot push or open issues or pull requests.
clessy/broker/clients.go

80 lines
1.2 KiB
Go
Raw Normal View History

2016-02-08 13:47:10 +00:00
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"net"
2016-02-09 14:55:37 +00:00
"github.com/hamcha/clessy/tg"
2016-02-08 13:47:10 +00:00
)
var clients []net.Conn
func startClientsServer(bind string) {
listener, err := net.Listen("tcp", bind)
assert(err)
// Accept loop
for {
c, err := listener.Accept()
if err != nil {
log.Printf("Can't accept client: %s\n", err.Error())
continue
}
clients = append(clients, c)
go handleClient(c)
}
}
func handleClient(c net.Conn) {
b := bufio.NewReader(c)
defer c.Close()
// Start reading messages
2016-02-20 21:33:09 +00:00
buf := make([]byte, 0)
2016-02-08 13:47:10 +00:00
for {
2016-02-20 21:33:09 +00:00
bytes, isPrefix, err := b.ReadLine()
2016-02-08 13:47:10 +00:00
if err != nil {
break
}
2016-02-20 21:33:09 +00:00
buf = append(buf, bytes...)
if isPrefix {
continue
}
// Get command
2016-02-08 13:47:10 +00:00
var cmd tg.ClientCommand
2016-02-20 21:35:26 +00:00
err = json.Unmarshal(buf, &cmd)
2016-02-08 13:47:10 +00:00
if err != nil {
2016-02-09 10:04:27 +00:00
log.Printf("[handleClient] Can't parse JSON: %s\r\n", err.Error())
2016-02-20 21:35:26 +00:00
log.Printf("%s\n", string(buf))
2016-02-08 13:47:10 +00:00
continue
}
2016-02-20 21:33:09 +00:00
// Empty buffer
buf = []byte{}
2016-02-20 20:40:24 +00:00
executeClientCommand(cmd, c)
2016-02-08 13:47:10 +00:00
}
removeCon(c)
}
func removeCon(c net.Conn) {
2016-02-08 16:57:27 +00:00
for i, con := range clients {
2016-02-08 13:47:10 +00:00
if c == con {
clients = append(clients[:i], clients[i+1:]...)
}
}
}
func broadcast(message string) {
for _, c := range clients {
2016-02-10 16:31:14 +00:00
_, err := fmt.Fprintln(c, message)
2016-02-08 13:47:10 +00:00
if err != nil {
removeCon(c)
}
}
}