package main import ( "bufio" "fmt" "net/url" "os" "strings" "time" "git.wenlab.co/joe/nnet" "git.wenlab.co/joe/nnet/cpn" ) var ( clt nnet.IHub ) type ClientSessionCb struct { } func (self *ClientSessionCb) OnClosed(ses nnet.ISession, reason int32) { fmt.Printf("session num: %d\n", clt.GetSessionNum()) fmt.Fprintf(os.Stdout, "lost connection %v, id:%v, reason:%v\n", ses.ServerAddr(), ses.Id(), reason) clt.StartReconn(ses.ServerAddr(), ses.Id()) } func (self *ClientSessionCb) OnConnected(ses nnet.ISession) (bool, int32) { fmt.Printf("connected to %s\n", ses.ServerAddr()) return true, 0 } func (self *ClientSessionCb) OnMessage(ses nnet.ISession, packet nnet.IPacket) bool { p, ok := packet.(*EchoPacket) if !ok { return false } fmt.Fprintf(os.Stdout, "echo from server: id<%v>, msg<%v>\n", p.Id, p.Msg) // dispatch(ses, p) return true } func (self *ClientSessionCb) OnHeartbeat(ses nnet.ISession) bool { p := &EchoPacket{ Id: 2, Msg: "heartbeat", } _ = ses.AWrite(p, time.Second) return true } func start_tcp_client() { __start_client(func() nnet.IHub { clt := cpn.NewTcpClient(&nnet.DefHubConfig, &ClientSessionCb{}, &TcpProtocol{}, cpn.WithReconn(3*time.Second)) err := clt.NewConnection(SERVER_ADDR, 5) if err != nil { panic(err) } return clt }) } func start_ws_client() { __start_client(func() nnet.IHub { clt := cpn.NewWsClient(&nnet.DefHubConfig, &ClientSessionCb{}, &WsProtocol{}, cpn.WithReconn(3*time.Second)) u := url.URL{ Scheme: "ws", Host: SERVER_ADDR, Path: WS_PATH, } err := clt.NewConnection(u.String(), 5) if err != nil { panic(err) } return clt }) } func __start_client(fn func() nnet.IHub) { clt = fn() reader := bufio.NewReader(os.Stdin) fmt.Println("Type what you want to send to server:") for { fmt.Print("->") line, _ := reader.ReadString('\n') line = strings.Replace(line, "\n", "", -1) p := &EchoPacket{ Id: 1, Msg: line, } ses, err := clt.GetSession(5) if err == nil { err = ses.AWrite(p, time.Second*3) if err != nil { fmt.Println("ERROR:", err) continue } } else { fmt.Println("not found session") } if line == "quit" || line == "q" { break } } // for clt.Stop() }