Golang Socket Programming

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The OSI reference model divides the computer network structure into 7 levels, but in the actual development application, we more recognize the TCP/IP family protocol five layer structure, namely Application layer (HTTP, FTP, DNS), Transport layer (UDP, TCP), Network layer (IP), link layer (Ethernet), physical layer.

Socket programming as a network layer and transport layer based data IO mode is mainly divided into two kinds, TCP sockets and UDP sockets, that is, the connection-oriented streaming socket and non-connected datagram socket.

Today mostly talk about Golang's TCP socket programming. Let's start with a simple example.

Server.go

Impersonation server-side func main () {tcpserver, _: = Net. RESOLVETCPADDR ("Tcp4", ": 8080") listener, _: = Net. LISTENTCP ("TCP", TCPServer) for {//when there is a new client request coming, get the connection to the client conn, err: = Listener. Accept () if err! = Nil {fmt.        PRINTLN (ERR) continue}//processing logic GO handle (conn) }}FUNC HANDLE (conn net. Conn) {defer Conn.                                                                                                                                                                                                                                             Close () Read the message sent by the client go func () {response, _: = Ioutil. ReadAll (conn) fmt. PRINTLN (String (response))} ()//sends a message to the client time. Sleep (1 * time. Second) Now: = time. Now (). String () Conn. Write ([]byte (now)})

Client.go

 //Impersonation client func main () {if Len (OS. Args) < 2 {fmt. fprintf (OS. Stderr, "Usage:%s host:port", OS. Args[0])}//Get command line parameters for socket address server: = OS. Args[1] addr, err: = Net. RESOLVETCPADDR ("TCP4", server) CheckError (ERR)//Establish TCP connection conn, err: = Net. Dialtcp ("TCP4", nil, addr) checkerror (ERR)//Send data to the server _, err = conn. Write ([]byte ("head/http/1.0\r\n\r\n")) CheckError (ERR)//Receive response response, _: = Ioutil. ReadAll (conn) fmt. PRINTLN (String (response)) OS.                                                                                                                                                                                                                                             Exit (0) }func checkerror (err error) {if err! = Nil {fmt. PRINTLN (ERR) OS. Exit (1)}}  

The overall approximate flow is:

Server-side first listens to port 8080 through the TCP protocol, then when there is a client to access it can read the information and write the response information, note here conn, err: = Listener. The Accept () statement is used to get the next call to the connection, and if it has not been connected, it will be in a blocked state.

The client attempts to establish a connection with the server through DIALTCP, sends the data to and receives the response after the connection succeeds, and in the above code, the connection is invalidated only after the connection is closed by the server side, otherwise the connection will remain in the established state. If the author will defer Conn. After the Close () comment is dropped, the connection to the 8080 port is viewed, and a connection is found to exist:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.