tcp客户端连续发生1000个json格式的学生信息字符串:
import ( "encoding/json" "fmt" "log" "net" "strconv" ) type student struct { Name string `json:"name"` Age int `json:"age"` } func main() { conn, e := net.Dial("tcp", "127.0.0.1:8888") if e != nil { log.Fatal(e.Error()) return } defer conn.Close() //send for i := 0; i < 1000; i++ { stu := student{"name_" + strconv.Itoa(i), i} bytes, e := json.Marshal(stu) if e != nil { log.Fatal(e.Error()) return } fmt.Println(string(bytes)) _, e = conn.Write(bytes) if e != nil { log.Fatal(e.Error()) return } } }
tcp服务端每次读取1024个字节
package main import ( "fmt" "io" "log" "net" ) func main() { l, e := net.Listen("tcp", ":8888") if e != nil { log.Fatal(e.Error()) return } defer l.Close() for { conn, e := l.Accept() if e != nil { log.Fatal(e.Error()) break } go handleConn(conn) } } func handleConn(conn net.Conn) { buf := make([]byte, 1024) for { n, err := conn.Read(buf) if err == io.EOF { fmt.Println("读取完毕。。。。。。") break } else if err != nil { fmt.Println(err.Error()) break } fmt.Printf("n=%d,content=%s ", n, string(buf[:n])) } }
每次读到的内容,出现粘包现象,如下: