Golang TCP socket programming is similar to HTTP and also a request response method. TCP requests (IP address, protocol, and port) are similar to HTTP requests, now we can simulate a request and a response. The request party is called the client. go
Package mainimport ("FMT" "IO/ioutil" "Net" "OS") func main () {tcpaddr, err: = net. resolvetcpaddr ("tcp4", "127.0.0.1: 7777") // obtain a TCP address, tcpaddrcheckerror (ERR) Conn, err: = net. dialtcp ("TCP", nil, tcpaddr) // create a TCP connection: tcpconncheckerror (ERR) _, err = Conn. write ([] Byte ("head/HTTP/1.0 \ r \ n") // send the HTTP Request Header checkerror (ERR) result, err: = ioutil. readall (conn) // obtain the returned data checkerror (ERR) FMT. println (string (Result ) OS. Exit (1)} func checkerror (ERR error) {If Err! = Nil {FMT. fprintf (OS. stderr, "Fatal error: % s", Err. Error () OS. Exit (1 )}}
The reply party is called server. Go.
Import ("FMT" "Net" "OS" "time") func main () {tcpaddr, err: = net. resolvetcpaddr ("tcp4", ": 7777") // obtain a tcpaddrcheckerror (ERR) listener, err: = net. listentcp ("TCP", tcpaddr) // listen to a port checkerror (ERR) for {Conn, err: = listener. accept () If Err! = Nil {continue} daytime: = time. now (). string () Conn. write ([] Byte (daytime) Conn. close () }} func checkerror (ERR error) {If Err! = Nil {FMT. fprintf (OS. stderr, "Fatal error: % s", Err. Error () OS. Exit (1 )}}
Golang TCP socket