[Golang] write from zero to socket Server (3): Processing strategy for long and short connections (analog heartbeat)

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

Through the first two chapters, we succeeded in writing out a set of server and client that could be used, and communicated through protocol between them. So, a simple socket communication framework has been embryonic, then we are going to do is to find a way to make this framework more stable, healthy ~

As a server that is likely to communicate with many clients, the first thing to ensure is the stability of the entire server running state, so it is very important to make sure that the connection is disconnected when the client establishes the connection, otherwise, once the long connection is not closed, The use of server resources is scary. Therefore, we need to set different throttling strategies for possible short connections and long connections.

for short connections , we can use the timeout function that comes with net packages in Golang, a total of three, respectively:


Func (*ipconn) Setdeadlinefunc (c *ipconn) Setdeadline (t time. Time) Errorfunc (*ipconn) Setreaddeadlinefunc (c *ipconn) Setreaddeadline (t time. Time) Errorfunc (*ipconn) Setwritedeadlinefunc (c *ipconn) Setwritedeadline (t time. Time) Error


If you want to set a timeout for a short connection to the server, we can write this:

Netlisten, err: = Net. Listen ("TCP", Port) Log ("Waiting for Clients") for {conn, err: = Netlisten.accept () if err! = Nil {continue}conn. Setreaddeadline (time. Now (). ADD (time. Duration (Ten) * time. Second))
The three functions here are used to set the maximum length of time each socket connection can sustain, and once the set timeout is exceeded, it is automatically disconnected on the server side. where Setreadline, Setwriteline sets the maximum duration of reads and writes, while Setdeadline contains Setreadline, setwriteline two functions.

With this setting, the client connection for each server communication is no longer than 10s.


After the short connection, the next step is the processing strategy for the long connection ~ ~

As a long connection, since it is often difficult to determine when the connection will be interrupted, so it is not as simple as the short connection to set a timeout can be done, and in the Golang net package, there is no long-connected function, So we need to design and implement our own processing strategy for long connections.

For Socke long connections, it is common practice to design a communication mechanism between the server and the socket, and when there is no information interaction between the two, the two parties will periodically send packets (heartbeats) to maintain the connection status.


This method is currently used relatively more than the practice, but the cost is relatively large, especially when the server and multiple clients to maintain a long connection, concurrency is relatively high, considering the business needs of the company, I finally chose a relatively simple logic, relatively inexpensive strategy:

When the server receives the message from the client each time, it starts the heartbeat, and if it does not receive the client's message again before the heartbeat is finished, the connection to the client is disconnected. Once the client's message is received again within a set time, the server resets the timer and restarts the heartbeat again until the timeout is disconnected.

Here is the code to implement the timing:

Long Connection entry Func handleconnection (conn net. conn,timeout int) {buffer: = make ([]byte, 2048) for {n, err: = Conn. Read (buffer) if err! = Nil {LOGERR (conn). Remoteaddr (). String (), "Connection error:", err) Return}data: = (Buffer[:n]) Messnager: = Make (chan byte) Postda: =make (chan byte)//Heartbeat timing Go heartbeating (conn,messnager,timeout)//detects if the client has data from Go Gravelchannel (data,messnager) Log ("Receive data length : ", N) Log (Conn. Remoteaddr (). String (), "Receive data string:", String (data}}//heartbeat timing, based on Gravelchannel to determine whether the client sends information func heartbeating (conn net) within the set time. Conn, Readerchannel chan byte,timeout int) {Select {case FK: = <-readerchannel:log (Conn. Remoteaddr (). String (), "Receive data string:", String (FK)) Conn. Setdeadline (time. Now (). ADD (time. Duration (Timeout) * time. Second))//conn. Setreaddeadline (time. Now (). ADD (time. Duration (5) * time. Second)) Breakcase <-time. After (time. SECOND*5): Log ("It ' s really weird to get nothing!!!") Conn. Close ()}}func gravelchannel (n []byte,mess Chan byte) {for _, V: = range n{mess <-v}Close (mess)}func log (v. ... interface{}) {log. Println (v ...)}


In this way, we can successfully implement the processing of long connections ~ ~, we can test this:

Func Sender (Conn net. Conn) {for i: = 0; I <5; i++ {words:= StrConv. Itoa (i) + "This was a test for long Conn" Conn. Write ([]byte (words)) time. Sleep (2*time. Second)}fmt. PRINTLN ("Send Over")}

can be found that When the Time.sleep blocking time in the sender function is shorter than the timeout in server, the client's information can be sent freely to the end of the loop, and when we set the sender function to block for a long time, we can only emit the information of the first loop.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.