func ClientReader(user *User, c net.Conn) { data := make([]byte, 4096) // 4096 byte slice (dynamic resize) for { n, err := c.Read(data) if err != nil { if DEBUG { gs.Log("Fail Stream read, err : ", err) } break } // header - body format (header + body in single line) messageType := gs_protocol.Type(gs.ReadInt32(data[0:4])) if DEBUG { gs.Log("Decoding type : ", messageType) } rawData := data[4:n] // 4~ end of line <--if fail read rawData, need calculated body size data (field) handler, ok := msgHandlerMapping[messageType] if ok { handler(user, rawData) // calling proper handler function } else { if DEBUG { gs.Log("Fail no function defined for type", handler) } break } } // fail read user.exit <- struct{}{} }
func main() { client, err := net.Dial("tcp", "127.0.0.1:8000") if err != nil { fmt.Println(err) return } defer client.Close() data := make([]byte, 4096) exit := make(chan struct{}) var userID int64 var method int fmt.Println("=================================================================") fmt.Println(" Input user ID (it must be a whole number greater than 0") fmt.Println("=================================================================") fmt.Print("userID : ") fmt.Scanln(&userID) ReqLogin(client, userID, data) go func() { for { fmt.Println("=================================================================") fmt.Println(" Input command number (1~5)") fmt.Println("=================================================================") fmt.Println("1. room list") fmt.Println("2. room create") fmt.Println("3. join") fmt.Println("4. action1") fmt.Println("5. quit") fmt.Print("choose number: ") fmt.Scanln(&method) switch method { case 1: ReqRoomList(client, userID, data) case 2: ReqCreate(client, userID, data) case 3: var roomID int64 fmt.Print("input room id : ") fmt.Scanln(&roomID) ReqJoin(client, userID, data, roomID) case 4: ReqAction1(client, userID, data) case 5: ReqQuit(client, userID, data) fmt.Println("program exit..bye") exit <- struct{}{} return default: continue } } }() go func() { data := make([]byte, 4096) for { n, err := client.Read(data) if err != nil { gs.Log("Fail Stream read, err : ", err) break } messageType := gs_protocol.Type(gs.ReadInt32(data[0:4])) gs.Log("Decoding type : ", messageType) rawData := data[4:n] handler, ok := msgHandlerMapping[messageType] if ok { handler(rawData) } else { gs.Log("Fail no function defined for type", handler) break } } }() <-exit }