Пример #1
0
func Recived_back(conn net.Conn) {

	conn_c := gochat.NewConn(conn)

	for {
		data, err := conn_c.Recv()
		if err != nil {
			fmt.Printf("读取返回数据错误 %s", err)
			break
		}

		msg := gochat.HiMsg{}
		err = gochat.ParseMsg(data, &msg)
		if err != nil {
			fmt.Println("输入格式错误 :", err)
			fmt.Println("  data :", string(data))
			continue
		}

		body := gochat.SendBody{}
		err = gochat.ParseMsg(msg.Body, &body)
		if err != nil {
			fmt.Println("输入格式错误 :", err)
			fmt.Println("  msg.Body :", msg.Body)
			continue
		}

		d := color.New(color.FgCyan, color.Bold)

		d.Print(body.From)
		fmt.Println(" : ", body.Msg)

	}
}
Пример #2
0
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)
			}
		}

	}
}