"Introduction to C language that can be understood with zero basis"-(13) Socket server writing

1. Learning objectives

  1. Understand the concept of socket in C language
  2. Understand the use of C language socket
  3. Complete the C language socket server

table of Contents

First: (a) from the Learning Myth
Two: (b) C language development is not so difficult to simply take you through the process
Title III: (c) easily understand the first C language program
Part IV: ( 4) Basic data types and variables of the language
Chapter 5: (5) Variables, constants and operations in C language
Chapter 6: (6) Easy to understand the logical operations of C language
Chapter 7: (7) C language The loop takes minutes to get started.
Chapter 8: (8) Understanding basic arrays is not that simple
. Chapter 9: (9) Two-dimensional arrays in C language and loop nesting.
Chapter 10: (10) Pointers in C language are the
tenth. A: (11) C language custom function is really simple

recommend

Welcome everyone to pay attention to the official account, every time the official account reaches 1024 or 1024 times, a lottery will be given to give a mechanical keyboard + 2 IT books~
Insert picture description here

Second, understand the use of socket sockets

Take a shot: you can use it if you don't understand the concept. If you don't understand it now, you will definitely understand it later. If the reader started to learn this article through my basic tutorial, I personally recommend that you become familiar with the knowledge points as much as possible before learning sockets, socket design other knowledge content, and familiar with the basic grammar and characteristics, otherwise it will cause some problems. If you really study, you can ask me if you have any questions~

Socket is also called a socket. It is an endpoint in a computer network where different hosts monitor and send carefully. This endpoint is an abstract concept. Like all designs that do not exist physically, it is an existence born under one rule.

2.1 Use socket

The following code is the code found on the Internet, some modifications have been made by myself. (I wrote it lazily, hahaha) This content only pays attention to the use process and is biased towards the application. Too much theoretical knowledge is no longer emphasized. For novices to learn socket, my personal suggestion is to first know how to "drop the package", first be a "pack-off man" to understand the problems better after completing the whole process, and for novices, some additional extended knowledge is not always A novice knows that if you really need to explain socket communication, you will design a lot of network layer content, so we first learn how to use sockets, and then we will sort out this knowledge.

Because the practice content of socket is too cumbersome for some novice steps, here is divided into two pieces, one for the server and one for the client to communicate. Compared with everyone who has studied the server and checked the client code again, you will feel It shines, the socket is just troublesome to use~ I wish you all good luck!

Socket is based on TCP/IP, presumably some students may be familiar with TCP/IP. Indeed, the word TCP/IP is very common when we learn programming. It is a protocol, and what is the protocol? Protocol means that when we are doing a certain thing, we stipulate some rules and standards to facilitate communication, and TCP/IP is a kind of protocol. Once again, we only need the socket to be based on the TCP/IP protocol, because in In the current tutorial, it is normal to talk about the agreement for a certain part of the reader. In fact, we can communicate with sockets without knowing the TCP/IP protocol, because the socket function we use is based on TCP/IP, which means that we only need to know how to use the socket.

Writing a socket in C language under Windows requires several steps. First, initialize WSAStartup, initialize the socket socket, and then cooperate with the binding information, and then bind the configuration information; after binding the information, pass This information is monitored by isten, if there is a link after monitoring, connect, and then start to use accept to receive the request. After receiving the request, you can choose to accept recv or send to send data, and finally closesocket closes the socket, and WSACleanup finally closes.

2.2 WSAStartup initialization

First initialize WSAStartup. The WSAStartup method receives 2 parameters, one is the version number of WinSock2, and the other is the pointer of WSADATA. Then we need to create an object of type WSADATA first, the code is:

WSADATA wsaData;

The WSADATA structure is used to store the information returned after WSAStartup is initialized. Since the information uses a pointer, in other words, it is an address, then the stored information will be saved after WSAStartup is initialized.

The first parameter received by WSAStartup is the version number. The version number can be directly generated by MAKEWORD. MAKEWORD(1, 1) means that the selected version number is 1. Then the WSAStartup initialization code can be written as:

WSAStartup(MAKEWORD(1, 1), &wsaData)

Since WSAStartup is equal to 0, it indicates that the initialization fails, and the program exits if the initialization fails. We can write:

WSADATA wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
{
    
    
	return 0;
}

2.3 socket creation

The socket method is used to create the socket. The socket receives 3 parameters, namely the IP type, the communication type, and the last parameter can be matched with the default type through the previously passed parameters. The IP type usually uses PF_INET to represent IPV4, the communication type uses TCP, and the last parameter uses 0 to indicate the default option for matching the IP type and the communication type previously set. The code is:

SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

After the creation is completed, determine whether the socket is created successfully, and return -1 if it fails:

if (slisten == -1)
	{
    
    
		printf("socket error !");
		return 0;
	}

2.4 IP binding

Next, start binding the listening IP address. Create a sockaddr_in structure variable.

struct sockaddr_in sin;

Then begin to bind the port and IP type, where INADDR_ANY represents the local machine and 6666 represents the listening port:

sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;

Then use bind to bind; bind receives 3 parameters, one is the socket created, one is the IP information to be bound, and the other is the length of the IP information. If the binding fails, it will return -1. The code is:

struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
    
    
	printf("bind error !");
	return 0;
}

Then use listen to monitor, listen to receive 2 values, one is the socket and the other is the number of queues, and it is ok to write 10. The code is:

if (listen(slisten, 5) == SOCKET_ERROR)
{
    
    
	printf("listen error !");
	return 0;
}

2.5 Information reception

Accept receives 3 parameters, the first is the socket, the second is the pointer of the sockaddr variable, and the third is the length of the received sockaddr. The code is:

struct sockaddr_in remoteAddr;
int nAddrlen = sizeof(remoteAddr);
sClient = accept(s, (SOCKADDR *)&remoteAddr, &nAddrlen);

After using accpet, it will wait until there is a link to execute the following code.
Then use recv to receive the text message sent by the client. recv receives 4 parameters, the first is the established communication, followed by an array, where the received data is stored, and the buffer size afterwards, the last parameter is generally set to 0. The code is:

char revData[255];
int ret = recv(sClient, revData, 255, 0);
printf(revData);

In the above recv function, sClient is the communication established using accpet, revData is the buffer area for receiving information, and 255 is the length.

Then send a piece of data to the client, and the user responds to the client's information request. Use send to send data to an established communication channel. The send function receives 4 parameters. The first is the established communication, the second is the data to be sent, the third is the length of the data to be sent, and the last is general settings. Is 0. The code is:

char * sendData = "你好鸭,我是CSDN 1_bit ,ID是A757291228~\n";
send(sClient, sendData, strlen(sendData), 0);

In the above recv function, sClient is the communication established using accpet, sendData is the data to be sent, and 255 is the length.
Finally, call the method to close the established communication:

closesocket(sClient);
closesocket(slisten);
WSACleanup();

Since it is a one-time communication, the program will be closed after running. Here we add a stop command before the code return0:

system("pause");

All dependent reference header files are as follows:

#include <winsock2.h>
#include <windows.h>
#include<stdio.h>
#include<stdlib.h>

The complete code is as follows:

#include <winsock2.h>
#include <windows.h>
#include<stdio.h>
#include<stdlib.h>
 
int main(int argc, char* argv[])
{
    
    
	//初始化WSADATA 
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
    
    
		return 0;
	}
 
	//创建scoket
	SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (slisten == -1)
	{
    
    
		printf("socket error !");
		return 0;
	}
 
	//绑定端口ip信息
	struct sockaddr_in sin;
	sin.sin_family = AF_INET;
	sin.sin_port = htons(8888);
	sin.sin_addr.S_un.S_addr = INADDR_ANY;
	if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
	{
    
    
		printf("bind error !");
		return 0;
	}
 
	//监听失败则返回
	if (listen(slisten, 5) == SOCKET_ERROR)
	{
    
    
		printf("listen error !");
		return 0;
	}
 

	SOCKET sClient;
	struct sockaddr_in remoteAddr;
	int nAddrlen = sizeof(remoteAddr);
	sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
	
	char revData[255];
	int ret = recv(sClient, revData, 255, 0);
	printf(revData);
	//发送信息
	char * sendData = "你好鸭,我是CSDN 1_bit ,ID是A757291228~\n";
	send(sClient, sendData, strlen(sendData), 0);
	
	closesocket(sClient);
	closesocket(slisten);
	WSACleanup();
	
	system("pause");
	return 0;
}

If errors are reported when using devc to copy the code, click Compile -> Compile Options:
Insert picture description here
Then add the following parameters in the window that appears:
Insert picture description here

to sum up

1. Understand the basic writing process of C language socket
. 2. Understand that writing C language socket under Windows requires several steps. First, initialize WSAStartup, initialize the socket socket, and then cooperate with the binding information, and then proceed The bind binding of the configuration information; after the information is bound, the isten monitoring is performed through the information, and if there is a link after the monitoring, connect, and then start to use accept to receive the request. After receiving the request, you can choose to accept recv or send to send data. Finally, closesocket closes the socket, and WSACleanup finally closes.

Guess you like

Origin blog.csdn.net/A757291228/article/details/109623705