Skip to content

Instantly share code, notes, and snippets.

@zhenzou
Last active May 10, 2018 04:29
Show Gist options
  • Select an option

  • Save zhenzou/65eb3e4007d88e7c81869ef3d352fc38 to your computer and use it in GitHub Desktop.

Select an option

Save zhenzou/65eb3e4007d88e7c81869ef3d352fc38 to your computer and use it in GitHub Desktop.
kcp_echo
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))
}
}
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