C + + Network programming summary _c language

Source: Internet
Author: User

The first time to write a program in C + + is only a rookie level of C #, but very familiar with C #. There is a great similarity between the two. But there are also differences.

First wrote a network communication with a small MFC program. Found

(1) MFC write interface really good trouble ah. C # write the tab minutes to fix things, with C + + harm I wrote for two days. The key is not skilled.  There are also icon displays for the list control controls. It's really troublesome.

However, since the last Detch () function is executed, it really shows up. These details are not usually written in the book.

(2) Use C + + to write the characteristics of the class, basically with C # is similar.

Let's talk about the problem of network programming.

1\ first did not know the C + + write program for the network socket, three kinds of different places. Always think I use the VS2013, with the highest level of socket should be easier, and then choose the CSocket result because this socket is blocking mode, the result is stuck, Stuck don't know how to do it. If the other side of the device does not respond, the most can not Deng it, this will not work.

Search on the Internet, found an article written to the CSocket plus timeout. Copy and do it again, but failed.  You can't find out why. According to the original article word comparison, also did not find out why. Failure to change train of thought

2\ thought the lower CAsyncSocket was asynchronous. It's always okay. But the callback function makes it inconvenient to handle. When you do the processing, you need information to handle it.

3\ so, to find the book, most of the book on the network part of just introduced a basic Socket, it looks very simple. Just try the basics first.

Did not think 30 minutes later, the network program test success. And there are timeout to receive, time out to send, and so on. It's my intention.

The original is the most basic, is the best.

To sum up:

How to operate the socket

The following is an example of a network client:

Client.cpp #include <iostream> #include <cstdio> #include <Winsock2.h> using namespace std; 
  int main () {//Load socket dynamic link library (DLL) WORD wversionrequested;  Wsadata Wsadata; 
    
  This structure is used to receive the WJNDOWS socket structure information of the int err;  wversionrequested = Makeword (1, 1); 
  Request version 1.1 of the Winsock library err = WSAStartup (wversionrequested, &wsadata);     if (Err!= 0) {return-1; The return value of zero indicates a successful request WSAStartup} if (Lobyte (wsadata.wversion)!= 1 | | 
    Hibyte (wsadata.wversion)!= 1) {//Check this low byte is not 1, high byte is not 1 to determine whether we are requesting the 1.1 version/otherwise, call WSACleanup () purge information, End function 
    WSACleanup ();  
  return-1; 
  //Create a socket operation, establish a streaming socket, return the socket font sockclient//socket socket (int AF, int type, int protocol); The first argument, specifies the address cluster (TCP/IP can only be af_inet or written as pf_inet)//second, select the type of socket (streaming socket), third, the specific address family related protocol (0 is automatic) socket sockclient = socket ( 
 
Af_inet, Sock_stream, 0); Connect socket sockclient to remote host//int connect (socket s, const struct sockaddr* name, inT namelen); 
  First parameter: Socket//second parameter requiring connection operation: Set the address information of the required connection//third parameter: the length of the address sockaddr_in addrsrv; Addrsrv.sin_addr. S_un.   S_ADDR = inet_addr ("127.0.0.1");  
  The local loop address is 127.0.0.1; 
  addrsrv.sin_family = af_inet; 
  Addrsrv.sin_port = htons (6000); 
 
  Connect (sockclient, (sockaddr*) &addrsrv, sizeof (SOCKADDR)); 
  Char recvbuf[100]; 
  Recv (Sockclient, recvbuf, 100, 0); 
 
  printf ("%s\n", recvbuf); 
 
  Send (Sockclient, "Attention:a client has enter...\n", strlen ("Attention:a client has enter...\n") +1, 0); 
  printf ("We can talk Five words"); 
  int n = 5; 
    do{printf ("\ n still%d times left:"); 
    Char talk[100]; 
    printf ("\nplease enter what you want to say next (\" Quit\ "to exit):"); 
    Gets (talk);     Send (Sockclient, talk, strlen (talk) +1, 0); 
    Send information char recvbuf[100]; 
    Recv (Sockclient, recvbuf, 100, 0);   printf ("%s Says:%s\n", "Server", recvbuf); 
 
  Receive Information}while (--N); 
  printf ("End linking...\n"); 
  Closesocket (sockclient);  WSACleanup (); To terminate the socket fontThe use of printf ("\ n"); 
  System ("pause"); 
return 0;

 }

about how to handle timeouts

In Send (), recv () process sometimes due to network conditions and other reasons, send and receive can not be expected, and set the transceiver timeout control:

What you need to be aware of in Linux is that the control structure of time is struct timeval instead of an integer.

This is written under Windows:

int NNETTIMEOUT=1000;//1 sec,
//Set Send timeout
setsockopt (Socket,sol_socket,so_sndtimeo, (char *) &nnettimeout, sizeof (int));
Sets the receive Timeout
setsockopt (Socket,sol_socket,so_rcvtimeo, (char *) &nnettimeout,sizeof (int));

This does not produce effect in Linux environment, must be defined as follows:

struct Timeval timeout = {3,0}; 
Sets the Send timeout
setsockopt (Socket,sol_socket,so_sndtimeo, (char *) &timeout,sizeof (struct timeval));

Sets the receive Timeout
setsockopt (Socket,sol_socket,so_rcvtimeo, (char *) &timeout,sizeof (struct timeval));

There are two points to note:

1) The fourth parameter of recv () needs to be Msg_waitall (set msg_dontwait can receive data without blocking after the connection is established), and in blocking mode the specified number of data will not be returned unless the timeout time expires. Also note that as long as the receive timeout is set, it is also effective in the absence of Msg_waitall. In the end, the timeout is not to let your program always wait there, to a certain time to return.

2) Even if the wait timeout value is not arrived, but the other side has closed the socket, then recv () will immediately return, and how much data returned how much data.

The above mentioned is the entire content of this article, I hope you can enjoy.

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.