1. What is socket
Socket, simply speaking, is the combination of IP address and port, which can communicate with the application of remote host。A host can be determined by IP address, and an application can be determined by port. IP + port can completely determine an application of a host. Socket originated from UNIX, similar to a special file, can be opened, closed, read and write operations. In a word, with socket, we can communicate with the host on the network.
2. TCP / UDP protocol
To carry out network communication, it is necessary to carry out certain rules. TCP / UDP is such a protocol, which stipulates the rules of communication.
TCP is a reliable, connection oriented two-way data transfer protocol.Reliability means that data will not be repeated 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, saying “I have received the data, you can send the next data”. After receiving the confirmation message, the sender will send the next data. In this way, the accuracy of the information can be determined. Two way transmission means that both sides can act as sender or receiver.
UDP is an unreliable, connectionless two-way transport protocol. UDP protocolJust send data, will not confirm whether you have received, only responsible for sending, not responsible for confirmation, so it is not reliable. UDP is suitable for the transmission of 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, which can be selected according to the demand.
3. A simple communication program
Use a simple example to illustrate the usage of socket. Socket program is generally divided into two parts, one is the server, the other is the client
The following describes the server-side creation process
1) First of all, there must be a socket to communicate. The function to create a socket is
int socket(int af, int type, int protocol);
AF: refers to the address family. AF is commonly used_ INET means to use IPv4 address, AF_ Inet6 indicates using IPv6 address
Type: the common transmission type is sock_ STREAM ,SOCK_ Dgram, streaming transmission, message transmission
Protocol: the commonly used protocol to use is “ipproto”_ TCP and ipptoto_ UDP refers to TCP and UDP protocol respectively
Returns a socket descriptor, which is an integer.
2) Using bind() function to determine various socket attributes
int bind(int sock, struct sockaddr *addr, socklen_t addrlen);
Socket: socket to bind
Addr: SOCKADDR address structure, which contains the protocol used, IP address, port, etc. Set your own
Addrlen: the size of SOCKADDR, which can be obtained by sizeof()
The following code shows the process of creating a socket and binding
//Use IPv4 address, TCP protocol
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN addr;
addr.sin_ addr.S_ un.S_ addr = htonl(ADDR_ Any); // indicates that any IP connection will be accepted
addr.sin_ family = AF_ INET; // use IPv4 address
addr.sin_ Port = htons (6666); // use port 6666
Bind (ServerSocket, & addr, sizeof (SOCKADDR)); // bind the socket to port 6666 and set the IP to be received
3) . listen function listen
After setting the properties, the server can start listening to monitor whether there is a client request connection.
Function prototype
int listen(int sock, int backlog);
Socket: socket
Backlog: how many customer service connections are allowed
4) The. Accept function waits for a connection
Accept is a blocking function. If there is no client clearing, the connection will wait here all the time
int accept(int sock, struct sockaddr *addr, socklen_t *addrlen);
Socket: socket,
addr:SOCKADDR structural morphology
addrlen:addr The length of can be obtained by sizeof
Pay attention to the return value of this function. It will return a new socket. This new socket is used to communicate with the client. The previous socket is a listening socket. You should distinguish it clearly.
5) . send / recv send / receive information
After successful connection with the client, you can communicate. The functions that can communicate include write / read, send / recv, etc. Here we introduce send / recv
int send(int sockfd, const char *buf, size_t len, int flags);
int recv(int sockfd, char*buf, size_t len, int flags);
Sockfd: socket
BUF: buffer for sending data
Len: length of sent data
Flags: flag, usually zero
6) The. Closesocket function closes the socket
Closesocket() closes the socket
Here is a complete server-side code
#include
#include
#pragma comment (lib,"ws2_32.lib")
int main()
{
Socket ServerSocket; // monitored socket
Socket newsocket; // socket used for communication
SOCKADDR_ In newaddr; // saves the socket address information of the client
SOCKADDR_ In addr; // address structure, including IP port
WSADATA data;
Word version; // socket version
int info;
Char buf [32]; // data buffer
/*
Before using socket, we need to set and initialize the version
Don't worry if you don't understand
*/
Version = makeword (2,2); // set version
info = WSAStartup(version, &data);
/*An application or DLL can only run after a successful wsastartup() call
To call further Windows Sockets API functions.
Initialize windows socket according to the version, and return 0 to indicate success
*/
if (info != 0)
{
Printf ("initialization failed";
return -1;
}
if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
{
Printf ("load failed";
WSACleanup();
return 0;
}
//Create socket, use TCP protocol
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
addr.sin_ addr.S_ un.S_ addr = htonl(ADDR_ Any); // indicates that any IP connection will be accepted
addr.sin_ family = AF_ INET; // use the IPv4 address
addr.sin_ Port = htons (6666); // set the port occupied by the application
Bind (ServerSocket, & addr, sizeof (SOCKADDR)); // bind the socket to the IP received on port 6666
Listen (ServerSocket, 3); // start listening. Is there a connection request from the customer service
Printf ("start listening, wait for connection......";
int len = sizeof(SOCKADDR);
newSocket=accept(serverSocket, (SOCKADDR*)&newAddr,&len);
Sprintf (buf, "welcome user connection for% s", INET_ ntoa( newAddr.sin_ addr));
Send (newsocket, buf, 32, 0); // send message
Printf ("connection successful, start sending message......";
Recv (newsocket, buf, 32, 0); // receive information
Printf ("received information is% s / N", buf));
Closesocket (newsocket); // close socket
}
Running results
Client example
The client is different from the server. The server is waiting for the connection, while the client is actively connecting, so the client does not listen or accept.
The client has a connect function to actively connect to the server. The rest is about the same
int connect(int sock, struct sockaddr *serv_addr, socklen_t addrlen);
Socket: socket
serv_ addr:SOCKADDR structural morphology
addrlen:serv_ The length of addr can be obtained by sizeof
Client code
#include
#include
#pragma comment(lib,"Ws2_32.lib")
int main()
{
SOCKET clientSocket;
SOCKADDR_IN addr;
int len;
char buf[32];
int info;
WSADATA data;
WORD version;
//Setting version and initialization
version = MAKEWORD(2, 2);
info = WSAStartup(version, &data);
if (info != 0)
{
Printf ("initialization failed";
return -1;
}
if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2)
{
Printf ("load failed";
WSACleanup();
return 0;
}
clientSocket = socket(AF_ INET, SOCK_ Stream, 0); // create socket
//The IP of the server to be connected, because the server is the local machine now, so write the local IP
//127.0.0.1 a special IP address, which means the IP address of the machine
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//The port should be the same as the server, otherwise it cannot be found
addr.sin_port = htons(6666);
//Use IPv4 address
addr.sin_family = AF_INET;
//Active connection server
connect(clientSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));
//Receive data sent by service
Recv (ClientSocket, buf, 32, 0); // receive data
Printf ("the message sent by the server is% s / N", buf));
Sprintf (buf, '% s','Hello, server');
//Send data
send(clientSocket, buf, 32, 0);
//Close socket
closesocket(clientSocket);
return 0;
}
Start the server first, then the client. A simple communication is done
Do this simple example, for socket should have a preliminary understanding, at least should learn how to use.
Next time use socket to write a simple chat program to further deepen the understanding of socket.