Last active
May 10, 2018 04:29
-
-
Save zhenzou/65eb3e4007d88e7c81869ef3d352fc38 to your computer and use it in GitHub Desktop.
kcp_echo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "encoding/binary" | |
| "github.com/xtaci/kcp-go" | |
| ) | |
| func Int2Bytes(i int) []byte { | |
| data := make([]byte, 4) | |
| binary.BigEndian.PutUint32(data, uint32(i)) | |
| return data | |
| } | |
| func main() { | |
| conn, err := kcp.DialWithOptions(":8081", nil, 10, 3) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer conn.Close() | |
| for { | |
| var input string | |
| fmt.Scanf("%s", &input) | |
| fmt.Println("input: len:", len(input)) | |
| if len(input) == 0 { | |
| continue | |
| } | |
| conn.Write(Int2Bytes(len(input))) | |
| conn.Write([]byte(input)) | |
| data := make([]byte, len(input)) | |
| conn.Read(data) | |
| fmt.Println("echo:", string(data)) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "net" | |
| "fmt" | |
| "encoding/binary" | |
| "github.com/xtaci/kcp-go" | |
| ) | |
| func Bytes2Int(data []byte) int { | |
| return int(binary.BigEndian.Uint32(data)) | |
| } | |
| func process(conn net.Conn) { | |
| var ( | |
| header = make([]byte, 4) | |
| err error | |
| n = 0 | |
| ) | |
| for { | |
| n, err = conn.Read(header) | |
| if err != nil || n != 4 { | |
| fmt.Printf("read %d err for %s\n", n, err.Error()) | |
| conn.Close() | |
| break | |
| } | |
| length := Bytes2Int(header) | |
| fmt.Println("length:", length) | |
| if length == 0 { | |
| continue | |
| } | |
| data := make([]byte, length) | |
| n, err = conn.Read(data) | |
| if err != nil { | |
| fmt.Printf("read %d err for %s\n", n, err.Error()) | |
| break | |
| } | |
| fmt.Println("recv:", string(data)) | |
| conn.Write(data) | |
| } | |
| } | |
| func main() { | |
| listener, err := kcp.ListenWithOptions(":8081", nil, 10, 3) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer listener.Close() | |
| for { | |
| conn, err := listener.Accept() | |
| if err != nil { | |
| println(err.Error()) | |
| conn.Close() | |
| break | |
| } | |
| go process(conn) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment