1. Usage:
(1) Define the remote IP address. Use Net. The Resolvetcpaddr () method, which defines a TCP address as the native listener address.
(2) Use net. The LISTENTCP ("TCP", LocalAddress) method starts listening and returns the TcpListener to the image.
(3) Accept the connection using the Tcplistener.accepttcp method. Returns: NET. Tcpconn to the statue.
(4) to net. Tcpconn Read and write operations on the image.
(5) Close the connection.
2. Code:
Package Mainimport ("FMT" "Io/ioutil" "NET") Func main () {localaddress, _: = Net. RESOLVETCPADDR ("TCP4", "127.0.0.1:8080")//define a native IP and port. var TcpListener, err = net. LISTENTCP ("TCP", localaddress) //At the newly defined address, listen for requests. If err! = Nil {fmt. PRINTLN ("Listen error:", err) Return}defer func () {//worry about the return before forgetting to close the connection, so make a pact in the defer to shut it down first. Tcplistener.close ()} () Fmt. Println ("Waiting to connect ...") var conn, err2 = TCPLISTENER.ACCEPTTCP ()//Accept connection. If err2! = nil {fmt. PRINTLN ("Accept Connection failed:", err2) Return}var REMOTEADDR = conn. REMOTEADDR ()//Gets the IP address of the connection to the image. Fmt. Println ("Received to a connection:", remoteaddr) fmt. PRINTLN ("reading message ...") var bys, _ = Ioutil. ReadAll (conn)//Read the contents of each other. Fmt. PRINTLN ("Message received to client:", String (bys)) Conn. Write ([]byte ("Hello, nice to meet you, my name is Songxingzhu"))//try to send a message. Conn. Close () //closes the connection. }
3. Operation Effect:
D:/application/go/bin/go.exe Build-i [D:/projects/gopath/source/demo/socket/server] Success: Process exit code 0.D:/Projects/GoPath /source/demo/socket/server/server.exe [D:/projects/gopath/source/demo/socket/server] waiting for connection ... Accept a connection: 127.0.0.1:47203 is reading the message ... Message received from the client: Get/http/1.1host:127.0.0.1:8080connection:keep-alivepragma:no-cachecache-control:no-cacheaccept:text /html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8upgrade-insecure-requests:1user-agent: mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/48.0.2564.116 safari/537.36accept-encoding:gzip, deflate, sdchaccept-language:zh-cn,zh;q=0.8 success: Process exit code 0.
Use the browser to do the auxiliary test.
Socket communication TCP Server in Go language