I have this TCP server:
package main
import (
"net"
"log"
"bufio"
"fmt"
)
func main() {
ln, err := net.Listen("tcp", ":8094")
if err != nil {
log.Println(err.Error())
}
aconns := make(map[net.Conn]int)
conns := make(chan net.Conn)
dconns := make(chan net.Conn)
msgs := make(chan string)
i := 0
go func() {
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err.Error())
}
conns <- conn
log.Println(conns)
}
}()
for {
select {
//read incoming messages
case conn := <-conns:
aconns[conn] = i
i++
//once we have the conection, read from it
go func(conn net.Conn, i int) {
rd := bufio.NewReader(conn)
for {
m, err := rd.ReadString('\n')
if err != nil {
break
}
msgs <- fmt.Sprintf("client %v: %v", i, m)
}
//done reading
dconns <- conn
}(conn, i)
case msg := <- msgs:
//broadcast to all connections
for conn:= range aconns{
conn.Write([]byte(msg))
}
case dconn := <-dconns:
log.Printf("client %v is gone\n", aconns[dconn])
delete(aconns, dconn)
}
}
}
Consider there are 3 clients chatting with eachother and another client comes in. How can I show previous texts to the new user? Is it doable?
Thanks.