TCP program development steps

TCP is a connection-oriented protocol, the two sides need to first establish a communication connection. Because reliable and stable characteristics of TCP, which is used in most applications, but its relatively high system resource requirements.

As shown in the development process the TCP protocol server procedure is as follows.

// initialize Winsock library for protocol version
 // create a service Socket object (specified protocol type, address, family information)
 // Bind Socket (specified IP, port binding to Socket)
 // start listening, and set the number of listeners . (after the start of monitoring, the client can connect successfully)
 // open the port to receive connections
 // send and receive data (using the Socket object to establish connection for communication)
 // close connection Socket
 // call termination Winsock library

Develop a TCP server program, the completion of initialization Winsock library and creates a socket (Socket) target after two general steps, we must complete the following steps.

(1) bind the socket to the specified IP address and port

No matter which protocol to use server-side program, must bind IP address and port of the server to the socket previously created, the client program to communicate with it. Function to bind a socket that bind, the following prototype.

int the bind ( 
 SOCKET S, // socket handle 
 const  struct the sockaddr FAR * name,     // the address to bind 
 int the namelen                          // address length specified by name 
);

The first parameter s is a socket handle to bind the address returned by the socket function.

The second parameter is a pointer to name sockaddr structure, is used to specify the address of the socket is bound.

For TCP, UDP protocol, the address is usually an IP address and port number for TCP, UDP protocol sockaddr_in structure instead of sockaddr. Which is defined below.

struct the sockaddr_in {
     Short   the sin_family;       // address family (address format), Windows as AF_INET 
    u_short The sin_port;        // port number 
    struct in_addr sin_addr; // the IP address of the 
    char   sin_zero for [ . 8 ];      // placeholder value, usually 0 
};

The first member of the same socket sin_family af function parameters.

The second member sin_port specifies the port number in the TCP or UDP communications services. The application should pay attention to when choosing a port number, such as 0 to 1023 by the IANA (Internet Assigned Numbers Authorith) management, reserved for a public service, common user application should select more than 1024 port number. Also note, the value used here is the network byte order, and the number is stored in the computer host byte order. Winsock library provides a set of conversion functions for converting between the two sequences, as shown below.

the htons u_short (u_short hostshort); // the type u_short byte order conversion by the host to network byte order 
u_long htonl (u_long hostlong);     // the type u_long byte order conversion by the host to network byte order 
u_short ntohs (u_short netshort);   // the type u_short converted from network byte order to host byte order 
u_long ntohl (u_long netlong);      // the type u_long converted from network byte order to host byte order

For example, we want to use port 6000, then it should be sin_port = htons (6000);

The third member sin_addr used to store the IP address, which is defined as a joint processing to the entire 32-bit value as defined below.

struct in_addr {
    union {
        struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
        struct { u_short s_w1,s_w2; } S_un_w;
        u_long S_addr;
    } S_un;

We know the IP address consists of four parts, each part separated by a point, usually the "xxx.xxx.xxx.xxx" format. An IP address is actually a 32-bit data, i.e., composed of four bytes, each byte of each part should be separated by dots. Therefore, the maximum value of each section is 255. If the direct use of the members of this string assignment, usually need to translate, Winsock library provides the following conversion functions.

unsigned long inet_addr(const char  FAR *cp);
char FAR * inet_ntoa(struct  in_addr in);

Wherein the action function is inet_addr 32-bit IP address value represented by the string registration change in network byte order.

Inet_ntoa action function is to convert the string representation of the IP address with the IP address in network byte order 32-bit value is represented.

The fourth member sin_zero sockaddr structure to same size set, no other meaning.

Function succeeds it returns 0, otherwise it returns SOCKET_ERROR, use WSAGetLastError function to get the error code.

(2) listen for connections

When the socket for binding specifies the IP address and port number should be set after the socket into the listening state, that is, listen for client connections. Use listen function prototype is as follows.

int the listen ( 
 SOCKET S,    // socket handle 
 int backlog   // listens maximum number of connections allowed to remain in the queue has not been processed 
);

In the case where the server set socket into the listening state, and the queue is not yet full, the client connection function can be connected successfully, otherwise the client connection handling function will block until the connection is successful or timed out.

(3) accepts the connection request

When the server socket into the listening state, then it should use the accept function accepts waiting in line connection, if there are connections waiting to return immediately to complete the connection, enter or accept the function will block until the arrival of connection, or socket object is shut down. accept function prototype is as follows.

Accept SOCKET ( 
SOCKET S, // socket handle 
struct the sockaddr FAR * addr, // pointer sockaddr_in structure, the other for receiving an address 
int FAR * addrlen      // addr pointer to memory size 
);

This function is taken on a socket connected to a first unprocessed s connections, then create a new socket and returns its handle to the connector, data transmission and reception using this new post is to complete the socket.

FIG TCP client program development process is as follows.

// initialize Winsock library for protocol version
 // create a service Socket object (specified protocol type, address, family information)
 // connection (to connect to the server specified IP and port)
 // send and receive data (Socket object using the established connection will be communication)
 // close connection Socket
 // terminate calls to the Winsock

As for the development of the TCP client program, the completion of initialization Winsock library and creates a socket (Socket) target after two general steps, the next step is to use the connect function initiates a connection to the server, the function prototype is as follows.

int Connect (SOCKET S,             // socket handle 
const  struct the sockaddr FAR * name, // pointer sockaddr_in structure, specified address of the server to connect 
int the namelen   // addr pointer to memory size 
);

Function succeeds returns 0, then s can send and receive data using a socket. Function fails to return SOCKET_ERROR, use function further WSAGetLastError get an error code.

Whether TCP protocol server program or client program, the data is sent using the send function prototype is as follows.

int send(
 SOCKET s,               //已建立连接的套接字句柄
 const char FAR *buf,    //要发送的内容所在内存首地址
 int len,                //发送内容的长度
 int flags               //指定调用方式,通常置为0
);

函数执行成功后返回实际发送数据的字节数。

接收数据使用recv函数,原型如下。

int recv(
 SOCKET s,          //已建立连接的套接字句柄
 char FAR *buf,     //要接收的内容所在内存首地址
 int len,           //接收数据缓冲区的长度
 int flags          //指定调用方式,通常置为0
);

函数执行成功后返回实际接收数据的字节数。在阻塞模式下,recv将阻塞线程的执行,直至接收到数据。

Guess you like

Origin www.cnblogs.com/cyx-b/p/12535263.html