With the development and popularization of Intenet, networks are widely used in embedded systems. More and more embedded devices use Linux operating systems. Linux is a free operating system with open source code and is highly portable. Therefore, it is increasingly important to study Socket network programming based on Linux.
[Attach] 900 [/attach]
Socket is actually a programming interface provided by the network transport layer to the application layer. The transport layer provides a logical channel for processes to ask questions on the basis of the network layer, while the process at the application layer uses the transport layer to communicate with a process on another host. Socket is the bridge between the application layer and the transport layer. 2.
[Attach] 901 [/attach]
When using Socket programming, you can develop client and server applications, which can communicate on the local network or over the Internet globally. Write and run the Socket client and server programs. Both parties establish service connection requests through the Socket and improve the performance of the Socket through some methods.
3 Socket programming
3.1 Socket type
There are three common types of sockets:
(1) stream Socket (SOCK_STREAM), which provides reliable communication streams and uses connection-oriented TCP protocol to ensure the correctness and sequence of data transmission:
(2) The datagram Socket (SOCK_DGRAM) data is transmitted through independent packets, which is unordered and not reliable and error-free. It defines a connectionless service, use the datagram protocol UDP;
(3) The original Socket (SOCK_RAM) allows direct access to the underlying protocol, which is powerful but inconvenient to use and mainly used for protocol development. The Socket written in this tutorial is a stream Socket.
3.2 Socket programming process
Socket programming adopts the customer/Server mode. Therefore, programming is divided into two parts: the server side and the client side.
Each Socket is represented by a semi-correlation description (protocol, local address, and local port). The Socket also has a function similar to the file opening function, which returns an integer Socket descriptor, then establish a connection, data transmission and other operations are implemented through Socket.
The programming process is as follows: the server first establishes a Socket and returns the Socket descriptor: configure the Socket port and IP address; create a * Number of sockets to check whether a client sends a request to the server, if yes, it will receive the request and put it in the receiving queue: accept a request from the receiving queue, and send the confirmation connection information to the client.
The client establishes a Socket and returns the Socket descriptor. It configures the Socket port and IP address, sends a connection request to the server, and receives the confirmation connection information sent back by the server. After the communication between the two parties ends, close the Socket. The basic functions used for Socket programming include socket (), bind (), listen (), accept (), connect (), send (), recv (), and close (). Figure 3 shows the Socket programming flowchart.
[Attach] 902 [/attach]
3.3 program compilation and running results
(1) Compile the server-side program serv. c and client program clt. c In the VI editor of Linux. Use the cross-compilation tool arm-linux-gcc to execute the compilation command to generate executable files.
The command is:
# Gcc serv. c = 0 serv
# Gcc clt. The c-0 clt
If there is no compilation error, the executable files serv and clt will be generated.
(2) configure the IP addresses of servers and clients to ensure smooth network connection. in serv. c, the IP address of the server has been set to 192.168.2.111. Set the IP address to 192.168.2.22 in "Network Settings" of the client. You can run the ping command to check whether the network is smooth.
(3) run the server program (. /serv), and then run the Client Program (. /clt 192.: 168.2.1l 1) you will see the result (Hello, Wang Lei! You are connected !); The running result 4 and figure 5 are shown. If you run the client program before running the server program, the system immediately prompts "Connect: Connection refused ".
4 SOCket Performance Optimization
4.1 solve multiplexing
The above operation only implements one client access. In actual situations, people often encounter multiple clients connecting to the server. Because connect (), recv (), and send () are both obstructive functions, if the resource is not ready, the process that calls the number of workers will enter the sleep state, i/O multiplexing cannot be processed. Add the select () function to serv. c on the server. It can use multiple sockets at the same time to achieve I/O multiplexing.
The function prototype is as follows:
[Attach] 903 [/attach]
This function monitors a series of file descriptors, especially readfds, writefds, and limit TFDs. If you want to know whether the data can be read from the standard input and socket descriptor sockfd, you just need to add the file descriptor "0" and "sockfd" to the set readfds. The numfds parameter should be equal to the value of the highest file descriptor plus 1 and set this value to sockfd + 1. Because it must be greater than the standard input file descriptor "0 ". When the select () function returns, the value of readfds is changed to reflect the selected file descriptor. After the client program is re-compiled and run, the server allows multiple clients to access the client. Result 6 is displayed.
[Attach] 904 [/attach]
4.2 minimize the delay of message transmission
When communication is performed through TCP socket, data is split into data blocks so that they can be encapsulated into the TCP payload (the payload in the TCP packet) of the given connection. The size of TCP payload depends on several factors (such as the maximum packet length and Path). To achieve better performance, use as much available data as possible to fill each packet. When there is not enough data to fill the payload (also known as the maximum segment length maximum segment size or MSS), TCP will use the Nagle algorithm to automatically connect some small buffers to one segment. In this way, the application efficiency can be improved by minimizing the number of sent packets, and the overall network congestion can be reduced.
Because this algorithm combines data and tries to form a complete TCP packet segment, some latency will be introduced. Socket network transmission only sends some small packets for a long time, such as the telnet program, which allows users to interact with the remote system, usually through a shell, if a user is required to fill a packet segment with characters entered before sending the packet, this method cannot meet the requirement. For example, in the HTTP protocol, the client browser usually generates a small request (an HTTP request message), and then the Web server returns a larger response (Web page ). Minimizing transmission latency is the first priority. In this case, the Socket can provide a solution to disable the Nagle algorithm. You can set the TCP_NODELAY socket option to disable the Nagle algorithm.
[Attach] 905 [/attach]
The experiment using Samba shows that disabling the Nagle algorithm almost doubles the read performance when reading data on the Samba drive on the server.
4.3 adjust the TCP window for Bandwidth Delay Product
The performance of TCP depends on several factors. The most important factor is the link bandwidth (the speed at which packets are transmitted over the network) and the round-trip time (round-trip time) or RTT (the delay between sending a message and receiving a response from the other end ). These two values determine the content called BDP (Bandwidth Delay Prod-uct. BDP provides a simple method to calculate the theoretically optimal TCP Socket buffer size (which stores data waiting for transmission in queue and waiting for the application to receive ). If the buffer is too small, the TCP window cannot be fully opened, which limits performance. If the buffer area is too large, valuable memory resources will be wasted. If the buffer size is set properly, the available bandwidth can be fully utilized.
BDP formula:
BDP = link bandwidth × RTT
If an application communicates over a 100 Mbit/s LAN and Its RRT is 500 ms, BDP is: 50 Mbit/s/sx0.050/8625 M = 625KB. The default TCP window size of Linux2.6 is 110KB, which limits the connection bandwidth to 22 Mb/s. The calculation method is as follows:
Throughput = window_size/RTT
110 KB/0.050 = 2.2 MB/s
Use the window size calculated above to get a bandwidth of 12.5 MB/s, that is:
625 KB/0 050 = 12.5 MB/s
The difference is great, and it can provide a larger throughput for the Socket. You can calculate the optimal buffer size based on your Socket. Socket provides several Socket options, two of which can be used to modify the size of the Socket sending and receiving buffer. Use the SO_SNDBUF and SO_RCVBUF options to adjust the size of the sending and receiving buffer.
[Attach] 906 [/attach]
In the Linux 2.6 kernel, the size of the sending buffer is defined by the calling user, and the receiving buffer is automatically doubled. By calculating the buffer size reasonably, the Socket network transmission bandwidth resources will be fully utilized, thus improving the transmission performance.
5 conclusion
Design and implement a Linux-based Socket network programming. By running the pre-compiled Executable File serv on the server side, and running the pre-compiled Executable File clt on the client side, establish a communication connection between the server and the client. After the select () function is added, the server can allow multiple clients to access the server, which solves the I/O multiplexing problem and is closer to the actual application. The TCP socket disable Nagle algorithm is used to minimize the delay of message transmission and improve the performance of Socket. In reality, network bandwidth is very precious. It is proposed to adjust the TCP window for the Bandwidth Delay Product, modify the size of the socket sending and receiving buffer, and make full use of available Bandwidth. Achieve Better network transmission performance. The actual network transmission environment is complex and changeable. Further analysis and research are required to achieve the optimal network transmission.