Let"s start with a simple piece of code:
Let"s start with a simple piece of code:
when the server executes conn.Close ()
, the server sends the FIN TCP packet to the client. After the client acknowledges, the TCP connection becomes half-open.
"half open" state means that the server can no longer send data to the client. Similarly, the client can send data out, so conn.Write ()
will not report an error. However, the last data sent by the client will not be received by the server.
you can use wireshark to grab packets and analyze the TCP protocol.
[1] https://en.wikipedia.org/wiki.
you have made a mistake in this way, where the code is commented.
package main
import (
"fmt"
"time"
"net"
)
func main() {
addr := "127.0.0.1:8999"
go func() {
tcpaddr, err := net.ResolveTCPAddr("tcp4", addr)
if err != nil {
panic(err)
}
listen, err := net.ListenTCP("tcp", tcpaddr)
if err != nil {
panic(err)
}
for {
if conn, err := listen.Accept(); err != nil {
panic(err)
} else if conn != nil {
go func(conn net.Conn) {
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(">", string(buffer[0 : n]))
}
conn.Close()//
}(conn)
}
}
}()
time.Sleep(time.Second)
// Client
if conn, err := net.Dial("tcp", addr); err == nil {
for i := 0; i < 2; iPP {
_, err := conn.Write([]byte("hello"))
if err != nil {
fmt.Println(err)
conn.Close()
break
} else {
fmt.Println("ok")
}
// sleep 10 seconds and re-send
time.Sleep(10*time.Second)
}
} else {
panic(err)
}
}
Previous: How to solve the problem of js scope?