[Network Programming 01] Basic knowledge of socket-simple network communication program

1. What is a socket

  Socket (socket), in simple terms is a combination of IP address and port (port), can communicate with the application of the remote host . A host can be determined by IP address, and an application can be determined by port. The IP + port can completely determine a certain application of a certain host. Socket originated from UNIX, similar to a special file, can be opened, closed, read and write operations. In short, with a socket, you can communicate with the host on the network.

2. TCP / UDP protocol

  To carry out network communication, certain rules must be imposed. TCP / UDP is such a protocol, which specifies the rules of communication.

  TCP is a reliable, connection-oriented two-way data transmission protocol. Reliability means that data will not be duplicated or lost. Whenever the sender sends a data to the receiver, if the receiver receives the data, it will send a confirmation message to the sender to indicate "I have received the data, you can send the next data", received confirmation After the message, the sender will send the next data. In this way, the information is correct. Bidirectional transmission means that both parties can act as senders or receivers.

  UDP is an unreliable, connectionless two-way transmission protocol. The UDP protocol only sends data and does not confirm whether you have received it. It is only responsible for sending and not for confirmation, so it is not reliable. UDP is suitable for transmitting video and the like, even if the video loses one or two frames, it will not have much impact.

  Socket can be based on TCP or UDP, just choose according to demand.

 

3. A simple communication program

  Use a simple example to illustrate the use of sockets. Programs written in sockets are generally divided into two parts, one is the server side and the other is the client side.

  The following describes the server-side creation process

  1). First, there must be a socket to communicate, the function to create a socket is

 

1 int socket(int af, int type, int protocol);

  af: indicates the address family, commonly used AF_INET indicates the use of IPV4 address, AF_INET6 indicates the use of IPV6 address

  type: The transmission type is commonly used SOCK_STREAM, SOCK_DGRAM, streaming, message transmission

  protocol: The protocols to be used are commonly IPPROTO_TCP and IPPTOTO_UDP, which respectively represent TCP and UDP protocols

  Returns a socket descriptor, which is an integer.

  2). Use the bind () function to determine various socket attributes

1 int bind(int sock, struct sockaddr *addr, socklen_t addrlen);  

  sock: the socket to be bound

  addr: SOCKADDR address structure, which contains the protocol used, IP address, port, etc. To set it yourself

  addrlen: The size of SOCKADDR, which can be obtained with sizeof ()

  The following code shows the process of creating a socket and binding

1  // Use IPV4 address, TCP protocol 
2 serverSocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
 3  SOCKADDR_IN addr;
 4 addr.sin_addr.S_un.S_addr = htonl (ADDR_ANY); // Indicates that any ip connection will accept 
5 addr.sin_family = AF_INET; // Use IPV4 address 
6 addr.sin_port = htons ( 6666 ); // Use port 6666 
7 bind (serverSocket, & addr, sizeof (SOCKADDR)); // Connect the socket to port 6666, Set the received IP binding

 3) .Listen function monitoring

  After setting the attributes, the server can start listening to monitor whether a client requests a connection.

  Function prototype

1 int listen(int sock, int backlog); 

  sock: socket

  backlog: how many client connections are allowed

 4) .Accept function waiting for connection

  accept is a blocking function, if there is no client to clear the connection will always wait here

1 int accept(int sock, struct sockaddr *addr, socklen_t *addrlen); 

  sock: socket,

  addr: SOCKADDR structure

  addrlen: The length of addr can be obtained with sizeof

  Pay attention to the return value of this function, it will return a new socket, this new socket is the socket used to communicate with the client, the previous socket is the listening socket, to be divided clear.

  5). Send / recv send / receive information

  After successful connection with the client, you can communicate. The functions that can communicate are write / read, send / recv, etc. Here we introduce send / recv

1 int send(int sockfd, const char *buf, size_t len, int flags);
2 
3 int recv(int sockfd, char*buf, size_t len, int flags);

  sockfd: socket

  buf: buffer for sending data

  len: the length of the data sent

  flags: flags, generally zero

  6). The closesocket function closes the socket

  closesocket () closes the socket

  Below is a complete server-side code

1 #include <stdio.h>
 2 #include <WinSock2.h>
 3 #include <windows.h>
 4  #pragma comment (lib, "ws2_32.lib")
 5  int main ()
 6  {
 7      SOCKET serverSocket; // Monitored socket 
8      SOCKET newSocket; // Socket used for communication 
9      SOCKADDR_IN newAddr; // Save the socket address information of the client 
10      SOCKADDR_IN addr; // Address structure, including ip port (port) 
11  
12      WSADATA data ;    
 13      WORD version; // socket version 
14      intinfo;
 15      char buf [ 32 ]; // Data buffer 
16      / * 
17         Set and initialize the version before using the socket
 18         Don't understand and don't
      care 19      * / 
20 version = MAKEWORD ( 2 , 2 ); / / set version 
21      info = WSAStartup (version, & the Data);
 22      / * application or DLL can only be successful WSAStartup () after calling
 23             before calling for further Windows Sockets API function.
24          Initialize the windows socket according to the version, and return 0 to indicate success
 25      * / 
26  
27      if (info! = 0 )
28      {
 29          printf ( " Initialization failed \ n " );
 30          return - 1 ;
 31      }
 32      if (LOBYTE (data.wVersion)! = 2 || HIBYTE (data.wVersion)! = 2 )
 33      {    
 34          printf ( " Loading failed \ n " );
 35          WSACleanup ();
 36          return  0 ;
 37      }
 38       // Create socket, use TCP protocol 
39      serverSocket =socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
 40      addr.sin_addr.S_un.S_addr = htonl (ADDR_ANY); // indicates that any ip connection will accept 
41      addr.sin_family = AF_INET; // use ipv4 address 
42      addr.sin_port = htons ( 6666 ); // Set the port occupied by the application 
43      bind (serverSocket, & addr, sizeof (SOCKADDR)); // Bind the socket to port 6666 and the received IP 
44      listen (serverSocket, 3 ); // Start monitoring, if there is a client requesting connection 
45      printf ( " Start monitoring, waiting for connection .......... \ n " );
 46      int len = sizeof(SOCKADDR);
 47      newSocket = accept (serverSocket, (SOCKADDR *) & newAddr, & len);
 48      sprintf (buf, " Welcome: user connection for% s " , inet_ntoa (newAddr.sin_addr));
 49      send (newSocket, buf , 32 , 0 ); // Send message 
50      printf ( "The connection is successful, start sending message ......... \ n " );
 51      recv (newSocket, buf, 32 , 0 ); // Receive Message 
52      printf ( "The received message is:% s \ n " , buf);
 53      closesocket (newSocket);// Close socket 
54 }

  operation result

  

 

  Client example

  The client is different from the server. The server is waiting for the connection, and the client is actively connecting, so the client does not have a listen function to listen, and there is no accept function to wait for the connection.

  The client has a connect function to actively connect to the server. Almost the rest

1 int connect(int sock, struct sockaddr *serv_addr, socklen_t addrlen);

  sock: socket

  serv_addr: SOCKADDR structure

  addrlen: length of serv_addr, can be obtained with sizeof

  Client code

  

 1 #include<stdio.h>
 2 #include<Windows.h>
 3 #include<Windows.h>
 4 #pragma comment(lib,"Ws2_32.lib")
 5 
 6 int main()
 7 {
 8     SOCKET clientSocket;
 9     SOCKADDR_IN addr;
10     int len;
11     char buf[32];
12     int info;
13     WSADATA data;
14     WORD version;
15     //设定版本,与初始化
16     version = MAKEWORD(2, 2);
17      info = WSAStartup (version, & data);
 18      if (info! = 0 )
 19      {
 20          printf ( " Initialization failed \ n " );
 21          return - 1 ;
 22      }
 23      if (LOBYTE (data.wVersion)! = 2 || HIBYTE (data.wVersion)! = 2 )
 24      {
 25          printf ( " Load failed \ n " );
 26          WSACleanup ();
 27          return  0 ;
 28      }
29      
30      clientSocket = socket (AF_INET, SOCK_STREAM, 0 ); // Create socket
 31      // The IP of the server to connect to, because the server is now the local machine, so write the local ip
 32      // 127.0.0.1 a special 'S IP address, which means the IP address of the machine 
33      addr.sin_addr.S_un.S_addr = inet_addr ( " 127.0.0.1 " );
 34      // The port must be the same as the server, otherwise 
35      addr.sin_port = htons ( 6666 );
 36      // Use IPV4 address 
37      addr.sin_family = AF_INET;
 38      // Proactively connect to the server 
39      connect (clientSocket, (SOCKADDR *) & addr, sizeof(SOCKADDR));
 40      // Receive data sent by the service 
41      recv (clientSocket, buf, 32 , 0 ); // Receive data 
42      printf ( " The information sent by the server is:% s \ n " , buf);
 43      sprintf (buf, " % s " , " Hello, server " );
 44      // Send data 
45      send (clientSocket, buf, 32 , 0 );
 46      // Close the socket 
47      closesocket (clientSocket);
 48      return  0 ;
 49 
50 }

 

  Start the server first, then the client. A simple communication is completed

      

 

 

 

Making this simple example, you should have a preliminary understanding of the socket, at least you should learn how to use it.

Next time use socket to write a simple chat program to further deepen the understanding of socket.

 

Guess you like

Origin www.cnblogs.com/duichoumian/p/12705832.html