This is a creation in Article, where the information may have evolved or changed.
I. Overview
The previous article describes the basic functions and structure types, where you can start to write server and client communication applet, the basic flow of communication is as follows:
If Listen the server is used to listen, then you can use no ResolveTCPAddr function.
Now let's write a server and client that implements the function: the client sends data to Server,server to return the data to uppercase.
Second, the service-side implementation
1 2 3 4 5 6 7 8 9 Ten One A - - the - - - + - + A at - - - - - in - to + - the
|
Package main Import ( "NET" "FMT" "Strings" ) func main(){ tcpaddr, err: = Net. Resolvetcpaddr ("TCP4", "localhost:8080") //Create a tcpaddr if err! = Nil{ FMT. PRINTLN (ERR) return } Tcplinstener, err: = Net. Listentcp ("TCP4", TCPADDR) //Start monitoring if err! = Nil{ FMT. PRINTLN (ERR) return } FMT. Printf ("Start listen:[%s]", tcpaddr) Tcpcoon, err: = Tcplinstener.accepttcp () //blocking, waiting for client to connect if err! = Nil{ FMT. PRINTLN (ERR) return } defer tcpcoon.close () //Remember to close the connection object data: = make ([]byte, 2048) N, err: = Tcpcoon.read (data) //Client connection, start reading data if err! = Nil{ FMT. PRINTLN (ERR) return } recvstr: = string(Data[:n]) FMT. Println ("RECV:", Recvstr) Tcpcoon.write ([]byte(strings. ToUpper (RECVSTR)) //Convert to uppercase and return to client }
|
Turn on the server and enter the listening state to wait for the client to connect:
Third, the client implementation
1 2 3 4 5 6 7 8 9 Ten One A - - the - - - + - + A at - - - - - in - to +
|
Package main Import ( "NET" "FMT" ) func main(){ tcpaddr, err: = Net. Resolvetcpaddr ("TCP4", "localhost:8080") //tcp connection address if err! = Nil{ FMT. PRINTLN (ERR) return } Tcpcoon, err: = Net. Dialtcp ("TCP4", nil, TCPADDR) //Establish connection if err! = Nil{ FMT. PRINTLN (ERR) return } defer tcpcoon.close () //Close senddata: = "HelloWorld" N, err: = Tcpcoon.write ([]byte(senddata)) //Send data if err! = Nil{ FMT. PRINTLN (ERR) return } FMT. Printf ("Send%d byte data success:%s", N, senddata) recvdata: = make ([]byte, 2048) N, err = Tcpcoon.read (recvdata) //Read Data if err! = Nil{ FMT. PRINTLN (ERR) return } recvstr: = string(Recvdata[:n]) FMT. Printf ("Response data:%s", RECVSTR)
|
Run the client and the server will respond to the client request:
The service side status is as follows:
At this point, a completed server and clinet are finished