func Recived(raw_conn net.Conn) { go Recived_back(raw_conn) r := bufio.NewReader(os.Stdin) for { msg, err := r.ReadString('\n') if err != nil { fmt.Printf("读取用户输入数据错误 %s", err) break } msg = msg[:len(msg)-1] sigbody := gochat.SendBody{To: "all", Msg: msg} s := gochat.GetJson(sigbody) reg := gochat.HiMsg{Cmd: "sendmessage", Body: s} regjson := gochat.GetJson(reg) // conn.Write(line) conn := gochat.NewConn(raw_conn) conn.Send(regjson) } }
func Registered(raw_conn net.Conn) { sigbody := gochat.SigBody{Name: name} s := gochat.GetJson(sigbody) reg := gochat.HiMsg{Cmd: "signup", Body: s} regjson := gochat.GetJson(reg) // conn.Write(line) conn := gochat.NewConn(raw_conn) conn.Send(regjson) }
func handleConn(conn_map map[string]*gochat.Conn, client_raw net.Conn) { client := gochat.NewConn(client_raw) pool := gochat.NewClientPool(conn_map) for { himsg := &gochat.HiMsg{} data, err := client.Recv() if err != nil { fmt.Printf("client %s was disconnected!\n", client.RemoteAddr()) username := pool.GetByConn(client) r_body := &gochat.SendBody{From: "gochat", Msg: username + " offline!"} r_body_b := gochat.GetJson(r_body) himsg.Body = r_body_b pool.SendToAll(himsg) pool.DelByConn(client) break } fmt.Println("data =", string(data)) err = gochat.ParseMsg(data, himsg) if err != nil { fmt.Println("输入格式错误 :", err) fmt.Println(" data :", data) client.Send([]byte(`{"name": "我", "msg": "笨蛋"}`)) continue } switch true { case himsg.Cmd == "signup": sigb := &gochat.SigBody{} err := gochat.ParseMsg([]byte(himsg.Body), sigb) if err != nil { fmt.Println("signbody格式错误") break } //往 map 里添加 client fmt.Println("sigb.Name=", sigb.Name) pool.Add(sigb.Name, client) case himsg.Cmd == "sendmessage": sendb := &gochat.SendBody{} err := gochat.ParseMsg([]byte(himsg.Body), sendb) if err != nil { fmt.Println("sendbody格式错误") break } if sendb.To == "all" { user_slice := sendb.GetUsers() if len(user_slice) > 0 { username := pool.GetByConn(client) r_body := &gochat.SendBody{From: username, Msg: sendb.Msg} r_body_b := gochat.GetJson(r_body) r_himsg := &gochat.HiMsg{Body: r_body_b} for _, user := range user_slice { pool.SendTo(user, r_himsg) } } else { username := pool.GetByConn(client) r_body := &gochat.SendBody{From: username, Msg: sendb.Msg} r_body_b := gochat.GetJson(r_body) himsg.Body = r_body_b pool.SendToAll(himsg) } } else { client_v, ok := pool.GetByUsername(sendb.To) if !ok { fmt.Println("没有找到该用户", sendb.To) client.Send([]byte("别烦我!")) continue } payload := gochat.GetJson(himsg) client_v.Send(payload) } } } }