服务端代码:
package main
import (
"fmt"
"log"
"net"
"sync"
"time"
)
var (
conns = make(map[string]net.Conn)//保存客户端连接
msgChan = make(chan string,100)//消息通道
lock sync.Mutex
)
func main() {
l, err := net.Listen("tcp",":9999")//创建tcp socket并监听
if err != nil {
log.Println("listen error:",err)
return
}
defer l.Close()
log.Println("server listen at:9999")
go listenMsgChan()
for {
conn, err := l.Accept()//接收客户端连接(阻塞)
if err != nil {
log.Println("Accept error:",err)
break
}
go handleConn(conn)//创建协程处理连接
}
}
//监听消息通道,发送给所有客户端
func listenMsgChan() {
for {
select {
case msg := <-msgChan:
// 把所有接收到的消息广播给所有客户端
// 发送消息通道
lock.Lock()
for _,conn := range conns {
conn.Write([]byte(fmt.Sprintf("[%s]%s",ftime(),msg)))
}
lock.Unlock()
}
}
}
//处理客户端的连接
f