socket programming (five) - client instance (TCP) client

First, the client side operation flow

  1.1 Load socket library (WSAStartup ())

  1.2 to create a socket (socket ()).

  1.3 connection request is issued (Connect ()) to the server.

  For the client, it does not need to bind, you can directly connect to the server. This can be through the establishment of a connection with the server function call to connect. Its function prototype is as follows:

int connect(SOCKET s, const struct Sockaddr FAR* name , int namelen);

parameter:

a) s: The client data socket for starting.

b) name: IP address and port information for the specified network host.

c) namelen: second length parameter.

Wants to establish a connection with the server, you first need to define an address structure (SOCKADDR_IN) variable, and assign its members, set the IP address and port number of the server, the same port where the ports need to save and server use, and use network byte order.

1.4  to communicate (receive and transmit information and the server (Send () / the recv ()) )

1.5 Close the socket  (closesocket () / WSACleanup () )

Second, the client instance

. 1 #include <winsock2.h>
 2 #include <the iostream>
 . 3  the using  namespace STD;
 . 4  int main ()
 . 5  {
 . 6      WORD wVersion;
 . 7      WSADATA WSADATA;
 . 8      int ER;
 . 9      // 1. Initialization version 
10      wVersion MAKEWORD = ( 1 , 1 );
 11      // loading socket library 
12 is      ER = WSAStartup (wVersion, & WSADATA);
 13 is      IF (ER =! 0 )
 14      {
 15          return -1 ;
 16      }
 17      // detecting socket 
18 is      IF (! LOBYTE (wsaData.wVersion) = 1 || hibyte (wsaData.wVersion) =! 1 )
 . 19      {
 20 is          return - 2 ;
 21 is      }
 22 is  
23 is      // 2. create a socket 
24      sOCKET our sock = socket (AF_INET, SOCK_STREAM, 0 );
 25      // 3. connection server 
26 is      SOCKADDR_IN Addr_In;
 27      addr_in.sin_family = AF_INET;
 28      addr_in.sin_port = the htons ( 7000 );
29      addr_in.sin_addr.S_un.S_addr the inet_addr = ( " 127.0.0.1 " );
 30      Connect (our sock, (the sockaddr *) & Addr_In, the sizeof (Addr_In));
 31 is      // 4. send or receive data 
32      char recvbuf [ 1024 ] ;
 33 is      the recv (our sock, recvbuf, strlen (recvbuf) + . 1 , 0 );
 34 is      COUT << " receives the server data: " << endl;
 35      char sendBuf [] = " window Socket test procedures " ;
 36      Send (our sock , sendBuf, sizeof(sendBuf), 0 );
 37 [      // 5. The close the socket 
38 is      the closesocket (our sock);
 39      WSACleanup ();
 40      System ( " PAUSE " );
 41 is      return  0 ;
 42 is }

Three, TCP / IP operating principle

 

Guess you like

Origin www.cnblogs.com/506941763lcj/p/11032808.html