go 及时通信-查询用户列表
package main import "net" //构件用户对象 type User struct { Name string Addr string C chan string Conn net.Conn Server *Server } //用户API func NewUser(conn net.Conn, server *Server) *User { //用户地址 userAddr := conn.RemoteAddr().String() user := &User{ Name: userAddr, Addr: userAddr, C: make(chan string), Conn: conn, Server: server, } //启动go程 go user.ListMessage() return user } //监听channel信息 func (this *User) ListMessage() { for { msg := <-this.C this.Conn.Write([]byte(msg + "\n")) } } //上线业务 func (this *User) OnLine() { //用户上线 this.Server.MapLock.Lock() this.Server.OnlineMap[this.Addr] = this this.Server.MapLock.Unlock() //发送消息 this.Server.BroadCast(this, "shangxianle") } //下线业务 func (this *User) OffLine() { this.Server.MapLock.Lock() delete(this.Server.OnlineMap, this.Addr) this.Server.MapLock.Unlock() //用户下线 this.Server.BroadCast(this, "xianxianle") } //用户端发消息 func (this User) sendMsg(msg string) { this.Conn.Write([]byte(msg)) } //消息业务 func (this *User) DoMessage(msg string) { if msg == "who" { this.Server.MapLock.Lock() for _, cli := range this.Server.OnlineMap { msg := "[" + cli.Name + "]" + "zaixian\n" this.sendMsg(msg) } this.Server.MapLock.Unlock() } else { this.Server.BroadCast(this, msg) } }