TCPIP Winsock Programming Points

xiaoxiao2021-03-06  36

Master TCP / IP Programming is a must-have a way for friends who want to become Hacker. Because I have limited capacity, everyone will still look at it! I believe that everyone knows it before TCP / IP programming, so there is not much nonsense. Using Winsock programming by synchronous and asynchronous mode, synchronous mode logic is clear, programming is focused on the application, in the predecessor multitasking operating system (WinNT, Win2K) is based on multi-threading efficiency basically reaches the level of asynchronous mode, should this be the following as synchronization Mode programming points.

1. Quick communication

Winsock's Nagle algorithm will reduce the transmission speed of small datagram, and the system is default to use Nagle algorithm, use

Int setsockopt

Socket S,

Int Level,

Int Optname,

Const Char Far * OptVal,

Int Optlen

); Function close it

example:

Socket sconnect;

Sconnect =: Ocket (AF_INET, SOCK_STREAM, IPPROTO_TCP);

INT BNODELAY = 1;

Int Err;

Err = setsockopt (

Sconnect,

Ipproto_tcp,

TCP_Nodelay,

(char *) & bnodelay,

SiZoEOF (BNodelay)); // Does not use a delay algorithm

IF (Err! = NO_ERROR)

Trace ("Setsockopt Failed for Some REASON / N") ;;

2, Socket SEGMENTSIZE and Transceiver buffer

TCPSEGMENTSIZE is the maximum length of a single datagram, and the system defaults to 1460, and the transmission and receiving buffer is 8192.

In the SOCK_STREAM mode, if a single transmission data exceeds 1460, the system will be divided into multiple datagram, and the other party will be a data stream, the application needs to increase the judgment of the broken frame. Of course, the size of the 1460 can be changed in a modified registry, but Micrcosoft believes that 1460 is the best efficiency parameter, which is not recommended.

In the industrial control system, it is recommended to turn off the Nagle algorithm, each time the data is less than 1460 bytes (recommended 1400), so that each time you send a complete datagram, reducing the fault processing of the other party on the data stream.

3. The blocking time of the connection function when the network is reduced in the synchronous mode

When the internet network in the synchronization mode is about 20 seconds, it can be used to determine whether the path to the service host is passage, or first ping the IP address of the other host.

A. The gethostbyAddr blocked time regardless of the success of about 4 seconds.

example:

Long Lport = 3024;

Struct SockAddr_in ServerHostAddr; // Serve Host Address

ServerHostaddr.sin_Family = AF_INET;

ServerHostaddr.sin_Port = :: Htons (u_short (lport));

ServerHostAddr.sin_addr.s_addr = :: inet_addr ("192.168.1.3");

Hostent * PRESULT = gethostbyaddr (const char *) &

(ServerHostaddr.sin_addr.s_addr), 4, AF_INET);

IF (null == prelud)

{

INT NERRORCODE = WsageTlasterror ();

Trace ("gethostbyaddr errorcode =% d", nerrorcode;}

Else

{

Trace ("GethostbyAddr% S / N", PRESULT-> H_NAME) ;;

}

B, using ping mode for about 2 seconds

Texture 4, synchronous mode to solve the RECV, Send blocking problem

Solve the SELECT function, check the read and write available status before the transceiver.

A, read

example:

TimeVal TV01 = {0, 1}; // 1 mS clock delay, actually 0-10 milliseconds

Int nselectret;

INT NERRORCODE;

FD_SET FDR = {1, Sconnect};

NSELECTRET =: ELECT (0, & fdr, null, null, & TV01); // Check readable status

IF (socket_error == nselectret)

{

Nerrorcode = wsagetlasterror ();

Trace ("SELECT Read Status ErrorCode =% D", NERRORCODE);

:: CloseSocket (Sconnect);

Goto reconnect (customer party), or serve the thread exits (service party);

}

IF (NSELECTRET == 0) // timeout occurs, unable to read

{

Continue to read the state or actively send it to the other party

}

Else

{

Read data

}

B, write

TimeVal TV01 = {0, 1}; // 1 mS clock delay, actually 9-10 ms

Int nselectret;

INT NERRORCODE;

FD_SET FDW = {1, Sconnect};

NSELECTRET =: ELECT (0, NULL, NULL, & FDW, & TV01); // Check-written status

IF (socket_error == nselectret)

{

Nerrorcode = wsagetlasterror ();

"Select Write Status ErrorCode =% D", NERRORCODE);

:: CloseSocket (Sconnect);

// goto reconnect (customer party), or service thread exit (service party);

}

IF (NSELECTRET == 0) // timeout occurs, buffer full or network busy

{

/ / Continue to check the status or listening state

}

Else

{

//send

}

5. Change the TCP to send and receive buffer size

The system defaults to 8192, which can be changed as follows.

Socket sconnect;

Sconnect =: Ocket (AF_INET, SOCK_STREAM, IPPROTO_TCP);

INT NRCVBUF = 1024 * 20;

INT Err = setsockopt

Sconnect,

Sol_socket,

SO_SNDBUF, // write buffer, read buffer to SO_RCVBUF

(char *) & nrcvbuf,

SizeOf (nrcvbuf);

IF (Err! = NO_ERROR)

{

Trace ("setsockopt error! / N");

}

Check if the buffer is set, check if it is really successful

INT GetSockopt

Socket S,

Int Level,

Int Optname,

Char far * Optval,

INT FAR * OPTLEN

);

6. Bind and Listen of the service party with multiple IP addresses

In applications with high reliability requirements, the dual network and multi-network channels are required, and the reputation is easy to implement, and the client can establish a customer request service for all IP addresses of the unit on port 3024 as follows. Socket HserveSocket_ds = invalid_socket;

Struct SockAddr_in Hostaddr_ds; // Server Host Address

Long Lport = 3024;

Hostaddr_ds.sin_family = AF_INET;

Hostaddr_ds.sin_port = :: htons (u_short (lport));

Hostaddr_ds.sin_addr.s_addr = HTONL (INADDR_Any);

HserveSocket_ds =: Ocket (AF_INET, SOCK_STREAM, IPPROTO_TCP);

IF (hserversocket_ds == invalid_socket)

{

AFXMessageBox ("Building Data Server Socket Failed!");

Return False;

}

IF (socket_error == :: bind (hserversocket_ds, (Struct)

SockAddr *) (& (Hostaddr_DS)), sizeof (sockaddr))))

{

INT NERRORCODE = WsageTlasterror ();

Trace ("Bind Error =% D / N", NERRORCODE;

AFXMessageBox ("Socket Bind Error!");

Return False;

}

IF (socket_error == :: listen (hserversocket_ds, 10)) // 10 customers

{

AFXMessageBox ("Socket Listen Error!");

Return False;

}

AfxBeginthread (ServerThreadProc, Null, Thread_Priority_NORMAL);

After the client is complex, after the connection is broken, the renewal should be connected to a IP address connection. It is also possible to use simultaneous ways to connect.

7, realize variant client / server with TCP / IP Winsock

Traditional client / server is asked by the customer, the service answer, and the transmission and reception are paired. The variant Client / Server refers to the classification of customers and services in the connection. After building a good communication connection, no longer have strict customers and services, any party can actively send, need or do not need to answer the application Words, this approach is useful in the industrial control industry, such as RTDB as a customer of I / O Server, but I / O Server can actively send switch state displacement to the RTDB, followed by information. It is largely reduced network communication load and improves efficiency.

转载请注明原文地址:https://www.9cbs.com/read-72279.html

New Post(0)