package main
import (
"fmt"
"net"
"sync"
)
var mux sync.RWMutex
var onlineUser = make(map[string]net.Conn)
var messageChan = make(chan string)
func main() {
listen, err := net.Listen("tcp", "127.0.0.1:8888")
if err != nil {
fmt.Printf("listen error %s ", err)
}
defer listen.Close()
go listenBroadMessage()
for {
conn, err := listen.Accept()
if err != nil {
fmt.Printf("conn error %s ", err)
}
go handlerConn(conn)
}
}
// listen broad message and send to all user
func listenBroadMessage() {
for {
msg := <-messageChan
fmt.Println("收到消息:" + msg)
for _, conn := range onlineUser {
conn.Write([]byte(msg))
}
}
}
//broadcast message
func broadMessage(conn net.Conn, message string) {
messageChan <- generateMessage(conn, message)
}
func generateMessage(conn net.Conn, msg string) string {
return "[" + conn.RemoteAddr().String() + "]" + " " + msg + " "
}
// handler each user
func handlerConn(conn net.Conn) {
addr := conn.RemoteAddr().String()
broadMessage(conn, "进入了房间")
mux.Lock()
onlineUser[addr] = conn
mux.Unlock()
var isQuit = make(chan bool)
go func() {
buff := make([]byte, 4098)
for {
n, _ := conn.Read(buff)
if n == 0 {
isQuit <- true
return
}
buffMsg := string(buff[:n-1])
if buffMsg != "" {
broadMessage(conn, buffMsg)
}
}
}()
for {
select {
case <-isQuit:
delete(onlineUser, addr)
broadMessage(conn, "离开了房间")
return
}
}
}
https://blog.csdn.net/weixin_42940826/article/details/82386275