Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of short connection and long connection and heartbeat package in socket

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Today, I will talk to you about the short and long connections in socket, as well as the sample analysis of heartbeats. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

Introduction to TCP connection

When TCP protocol is used in network communication, a connection must be established between server and client before real read and write operations.

When the read and write operation is complete and both parties no longer need the connection, they can release the connection.

The establishment of the connection requires three handshakes, while the release requires four handshakes.

Therefore, the establishment of each connection requires resource consumption and time consumption.

A classic three-way handshake:

Classic four-way handshake closing picture:

I. long connection and short connection

Persistent connection: means that multiple packets can be sent continuously on a single TCP connection

During the maintenance of a TCP connection, if no packets are sent, both parties need to send inspection packets to maintain the connection

Generally need to do their own online maintenance.

Short connection: when there is data exchange between the two sides of the communication, a TCP connection is established, and after the data is sent, the TCP connection is disconnected.

Banks generally use short connections.

Its advantage is that it is relatively simple to manage, the existing connections are all useful connections, and no additional control means are needed.

For example, http only connects, requests, and closes, and the process takes a short time. If the server does not receive a request within a period of time, it can close the connection.

In fact, long connection is relative to the usual short connection, that is, to maintain the connection state between the client and the server for a long time.

The operation process of long connection and short connection

The usual steps for short connection are:

Connect → data transfer → close the connection

A long connection is usually:

Connect → data transmission → keep connection (heartbeat) → data transmission → keep connection (heartbeat) →... → closes the connection

This requires a long connection to send packets (heartbeat) regularly when there is no data communication, in order to maintain the connection state.

The short connection can be closed directly when there is no data transmission.

When to use long connection, short connection?

Long connections are mostly used for frequent operations, point-to-point communication, and the number of connections should not be too many.

Each TCP connection requires a three-step handshake, which takes time. If each operation is connected first and then operated, then the processing speed will be much lower.

So after each operation is continuously opened, the next time the data packet is directly sent to OK, there is no need to establish a TCP connection.

For example, a long connection is used to connect to the database

Frequent communication with short connections will result in socket errors, and frequent socket creation is also a waste of resources.

Second, send and receive mode

1. Async

The sending and receiving of messages are separate, independent and independent of each other. This approach can be divided into two situations:

(1) Asynchronous duplex: receive and send in the same program, and two different child processes are responsible for sending and receiving respectively.

(2) Asynchronous simplex: receiving and sending are done by two different programs.

2. Synchronization

Message sending and receiving are carried out synchronously, waiting for the return message to be received after the message is sent.

The synchronization method generally needs to consider the timeout problem, that is, the message cannot wait indefinitely after the message is sent, and the timeout period needs to be set.

After this time, the sender no longer waits for the read return message, but directly notifies the timeout to return.

In a long connection, there is generally no condition to judge when reading and writing ends, so it is necessary to add a length header.

The read function first reads the length of the header, and then reads the message of the corresponding length according to this length.

three。 Simplex, half-duplex and full-duplex

According to the division of labor and the direction of signal transmission, communication can be divided into three ways:

Simplex,

Half-duplex,

Full duplex.

Duplex mode is mainly used in computer network, in which:

Local area network adopts half-duplex mode.

The metropolitan area network and wide area network adopt a full biennial approach.

1. Simplex (Simplex):

In the equipment of both sides of the communication, there is a clear division of labor between the transmitter and the receiver, and data can only be transmitted in a single fixed direction from the transmitter to the receiver.

Typical sending devices using simplex communication such as card readers of early computers and typical receiving devices such as printers.

two。 Half duplex (Half Duplex) mode:

The devices of both sides of the communication are both transmitters and receivers. The two devices can transmit data to each other, but they can only transmit data to one direction at a time.

For example, walkie-talkies are half-duplex devices because only one party can talk at a time.

3. Full duplex (Full Duplex) mode:

The devices of both sides of the communication are both transmitters and receivers, and the two devices can transmit data in both directions at the same time.

For example, the telephone is a full-duplex device because both parties can talk at the same time.

Http services like WEB generally use short links because long links consume a certain amount of resources for the server.

On the other hand, thousands or even hundreds of millions of clients with frequent connections like WEB sites will save some resources by using short connections.

If you use a long connection, and there are thousands of users at the same time, if each user occupies a connection, you can imagine.

Therefore, the amount of concurrency is large, but each user needs to use short connection when there is no need for frequent operation.

In short, the choice of long and short connections depends on the situation.

4. The simplest example program for long connection and heartbeat retention

/ *!

*

*\ File

*

*\ Brief

*

*\ Author

* Hank

*

, /

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# include

# define MAXBUF 1024

Int main (int argc, char * * argv)

{

Int sockfd, len

Struct sockaddr_in dest

Char buffer [MAXBUF]

Char heartbeat [20] = "hello server"

Fd_set rfds

Struct timeval tv

Int retval, maxfd =-1

If (argc! = 3)

{

Printf ("error! the right format should be:\"

\ n\ t\ t% s IP port\ n\ t eg:\ t%s127.0.0.1 80\ n "

Argv [0], argv [0])

Exit (0)

}

If ((sockfd = socket (AF_INET, SOCK_STREAM, 0))

< 0) { perror("Socket"); exit(errno); } bzero(&dest, sizeof(dest)); dest.sin_family = AF_INET; dest.sin_port = htons(atoi(argv[2])); memset(&(dest.sin_zero), 0, 8); if (inet_aton(argv[1], (struct in_addr*)&dest.sin_addr.s_addr) == 0) { perror(argv[1]); exit(errno); } if (connect(sockfd, (struct sockaddr*)&dest, sizeof(dest)) != 0) { perror("Connect"); exit(errno); } printf("\nReady to start chatting.\n\ Direct input messages and \n\ enter to send messages to the server\n"); while (1) { FD_ZERO(&rfds); FD_SET(0, &rfds); maxfd = 0; FD_SET(sockfd, &rfds); if (sockfd >

Maxfd)

Maxfd = sockfd

Tv.tv_sec = 2

Tv.tv_usec = 0

Retval = select (maxfd+1, & rfds, NULL, NULL, & tv)

If (retval =-1)

{

Printf ("Will exit and the select is error! s", strerror (errno))

Break

}

Else if (retval = = 0)

{

/ / printf ("No message comes, no buttons, continue to wait.\ n")

Len = send (sockfd, heartbeat, strlen (heartbeat), 0)

If (len

< 0) { printf("Message '%s' failed to send ! \ The error code is %d, error message '%s'\n", heartbeat, errno, strerror(errno)); break; } else { printf("News: %s \t send, sent a total of %d bytes!\n", heartbeat, len); } continue; } else { if (FD_ISSET(sockfd, &rfds)) { bzero(buffer, MAXBUF+1); len = recv(sockfd, buffer, MAXBUF, 0); if (len >

0)

{

Printf ("Successfully received the message:'% sailing bytes of data% d bytes of data\ n"

Buffer, len)

}

Else

{

If (len < 0)

Printf ("Failed to receive the message!\"

The error code is% d, error message is'% s'\ n "

Errno, strerror (errno))

Else

Printf ("Chat to terminate!\ n")

Break

}

}

If (FD_ISSET (0, & rfds))

{

Bzero (buffer, MAXBUF+1)

Fgets (buffer, MAXBUF, stdin)

If (! strncasecmp (buffer, "quit", 4)

{

Printf ("Own request to terminate the chat!\ n")

Break

}

Len = send (sockfd, buffer, strlen (buffer)-1,0)

If (len < 0)

{

Printf ("Message'% s' failed to send!\

The error code is% d, error message'% s'\ n "

Buffer, errno, strerror (errno))

Break

}

Else

{

Printf ("News:% s\ t send, sent a total of% d bytes!\ n"

Buffer, len)

}

}

}

}

Close (sockfd)

Return 0

}

After reading the above, do you have any further understanding of the short and long connections in socket and the sample analysis of heartbeats? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 271

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report