当前位置:网站首页>[network] socket programming
[network] socket programming
2022-06-11 03:56:00 【Suk-god】
List of articles
1、 Prerequisite knowledge paves the way
1.1 Understanding ports —port
The essence : The port number is a 2 byte 16 An unsigned integer of bits , The scope is [0,65535]
effect : The port number is used to identify a process , Tell the operating system , Which process should handle the current data
matters needing attention :A port can only be occupied by one process
A process can occupy multiple portsSome well-known ports :
[0,1023] Ports in scope are already used by some well-known protocols , We should not use the data in this range as the port number when writing code
MySQL----3306 port
Oracle----1521 port
1.2 Five tuple information of network data
{ Source IP、 Purpose IP 、 Source port 、 Destination port 、 agreement }
| name | effect |
|---|---|
| Source IP | Identify which host the network data is sent from |
| Purpose IP | Identify which host the data is going to |
| Source port | Identify the network data from “ Source IP” Which process of the corresponding host generated |
| Destination port | Through purpose IP After finding the destination host , You need to use the destination port to find the corresponding process |
| agreement | Calibrate the protocol used by both parties to transmit data , It's usually UDP/TCP |
1.3 Network byte order
Byte order Also known as Terminal sequence perhaps Tail sequence . It refers to the order in which multibyte data is stored in memory .
The byte order we touch falls into two categories : Small endian byte order and Big endian byte order
They are different rules for the order in which two kinds of data are stored in memory
| Byte order | characteristic |
|---|---|
| The small end Byte order | Data Low weight bit Of the corresponding space Low address |
| Big end Byte order | Data Low weight bit Of the corresponding space High address |
How to determine which storage rule your machine follows ?
Mode one : The pointer + Variable + Cast validation 
Mode two : Use the storage characteristics of the consortium to judge 
With the bedding on it , Let's learn about host byte order and network byte order
Host byte order : refer to The byte order of the machine itself , If it's big end , Then the host byte order is big end , If it's small end , Then the host byte order is small end
Network byte order : It is required to use when transmitting data through the network Big endian byte order transmitted
1.4 Conversion between host byte order and network byte order
Since the network byte order is the big end byte order , Now suppose there is AB Two hosts , They need to communicate with each other through the network , We analyze A towards B One way to send messages .
A towards B Data sent , When transmitted over the network Be sure to convert to network byte order , Otherwise, errors may occur in the transmitted data ( It depends on the host A Is it a big end or a small end machine )
B Receive... From the network A When sending data , Also needed Convert data from network byte order to B Host byte order of the host
This specific transformation process does not need to be implemented by us ,OS It provides us with a conversion interface

1.5 TCP Deal with the UDP The characteristics and differences of the protocol
UDP:
TCP
2、UDP_socket Programming
2.1 Programming flow
Server side
Ⅰ、 Create socket
Ⅱ、 Binding address information
Ⅲ、 Send and receive messages
Ⅳ、 Close the socket after useclient
Ⅰ、 Create socket
Ⅱ、 Binding address information is not recommended
It is not recommended to manually bind the address information in the code
Ⅲ、 Send and receive messages
Ⅳ、 Close the socket after use
Icon :
summary :
1、 Why create sockets ?
Bind the process to the network card , The process can receive messages from the network card , You can also send messages through the network card .
2、 What does binding address information do ?
binding IP And port . The purpose is to represent a host and a process in the network . thus , For the recipient , The sender will know which machine and which process the receiver is on ; For the sender , It can identify which process of which machine the network data is sent from .
2.2 Programming interface (API)
2.2.1 Create socket
#include<sys/socket.h>
int socket(int domain, int type, int protocol)
Parameters :
Return value :
2.2.2 Binding interface
int bind(int sockfd, const struct sockaddr* addr, socklen_t addrlen);
Parameters :
sockfd----- Socket descriptor returned when creating socket
addr----- Bound address information (IP + port)
addrlen---- The length of the bound address information
Be careful : there struct sockaddr Is a general data structure ! The structure is as follows :
When we organize parameters , What is passed is not the above general data structure , It is struct sockaddr_in This structural variable , The details are as follows :
2.2.3 Send interface
ssize_t sendto(int sockfd, const void* buf, size_t len, int flags,const struct sockaddr* dest_addr, socklen_t addrlen);
Parameters :
Return value :
2.2.4 Receiving interface
ssize_t recvfrom (int sockfd, void* buf, size_t len, int flags,struct sockaddr* src_addr, socklen_t* addrlen);
Parameters :
2.2.5 Close interface
int close(int fd)
2.3 Programming code

Specific code ----> Click here
3、TCP_socket Programming
3.1 Programming flow
Server side
Create socket
Binding address information
monitor
Get a new connection
Sending and receiving data
Close the connectionclient
Create socket
Binding address information is not recommended
A connection
Sending and receiving data
Close the connection
Icon :
summary :
The meaning of monitoring
monitor TCP New client connection , Establish with the client TCP Connect .( here ,TCP The establishment of is completed in the kernel )
Get the meaning of the new connection
Get the socket descriptor of the new connection , every last TCP The connection will generate a new socket descriptor
The meaning of initiating a connection
Initiate a connection to the server
3.2 Programming interface (API) ( a UDP Programming new interfaces )
3.2.1 Listening interface
int listen(int sockfd, int backlog)
Parameters
Return value
success —>0
Failure —>-1
3.2.2 Get a new connection
int accept(int sockfd, struct sockaddr* addr, socklen_t * addrlen);

Understanding of the interface for acquiring new connections :
3.2.3 A connection
int connect (int sockfd, const struct sockaddr* addr, socklen_t addrlen)


3.2.4 Sending and receiving data
receive data :
ssize_t recv(int sockfd, void* buf, size_t len, int flags);

Be careful : The return value is 0 Indicates that the opposite end has closed the connection , If the opposite end at this time refers to the client , Then the server needs to close the corresponding new socket descriptor !
send data
ssize_t send(int sockfd, const void* buf, size_t len, int flags)

Be careful :
Server side When sending data , The first parameter sockfd Delivered Is the newly created socket descriptor , Not a socket descriptor for listening sockets
3.3 Programming code
Expected functions : The server and multiple clients can communicate normally !
3.3.1 TCP_demo
Server side main code :
Client main code :
Run result analysis :
Analyze the reasons for this situation :
First , The code of the second client can be executed to the prompt for input statement , This indicates that the client and the server have established a connection . And no error is reported after the client sends the data , It indicates that the client data transmission is successful . So the problem must be the server code .
We can order netstat To view the current network connection status and related information .
in summary , Our single threaded TCP Code for now , Only serve a single client .( Be careful : Later, it can be multiplexed IO The model realizes that the server and client are one to many )
TCP_demo Client code
TCP_demo Server code
Based on this situation , We need to find a way , Multiple clients can enjoy services at the same time .
therefore , We can make a process on the server ( Threads ) Only responsible for establishing a connection with the client , The rest of the process ( Threads ) You can communicate with one client respectively . In this way, we can achieve our goal . therefore TCP Combine multiple processes / Multithreading stands out ~
Here are the introduction TCP Code combined with multiprocessing and multithreading
3.3.2 TCP + Multi process
First , For the client code , No changes are required ! Because the client only needs to communicate with the server all the time !
The main change is on the server side , We realize the separation of responsibilities by creating sub processes , That is, the parent process is only responsible for establishing a connection with the client , The subprocess is responsible for sending and receiving messages with the client .
The specific core code is as follows :
Pay attention to a few details :
1、 A child process is a copy of the parent process PCB, therefore The parent process needs to establish a connection with the client first , That is, in the parent process PCB Medium fd_array Create a child process after you have the file descriptor of the socket in
2、 The subprocess was created successfully , Because it only needs to send and receive messages with the client , So we just need accept The new socket descriptor returned is OK , So we need to Close the listening socket copied from the parent process
3、 If the client closes the connection , Then the child process needs to close the corresponding socket, that is, the file descriptor , Then the process needs to exit .
But notice : Exit time , Be sure to notify the parent process to receive the exit status information of the child process back and forth , Otherwise, the child process will program a zombie process ! But we can't use wait || waitpid To recycle . because wait Has blocking properties , and waitpid It needs to be used with a loop , Are not in line with our expectations . We It can be processed by semaphore , Namely rewrite SIGCHLD The signal !
Specific code reference TCP_process Server side
3.3.3 TCP + Multithreading


Specific code reference —TCP_thread Server code
That's about socket Summary of programming ~ Feel helpful friends welcome to comment and forward !!
边栏推荐
- [数据集]|无人机视角
- Jscpcp L. collecting diamonds (thinking)
- 6. 表格标签
- 难忘时刻
- Path count 2 (DP + number of combinations)
- [cnn]|differences between CNN and transformer
- OpenGL错误指南
- Manual testing cannot be changed to automated testing. What is missing?
- Detailed explanation of network time synchronization (NTP network timing) of video monitoring system
- OpenGl第九章 光照贴图
猜你喜欢

J. Balanced Tree

Guide de migration Maui

regular expression

Management system of College Students' associations based on SSM

VNC remote configuration of Galaxy Kirin server system

Pci/pcie related knowledge

Lvgl Chinese font production

基于SSM的大学生社团管理系统

Writing shell scripts using vscode

Pthread in the multithreaded Trilogy
随机推荐
Docker swarm installs redis cluster (bitnami/redis cluster:latest)
UML series articles (28) architecture modeling - collaboration
[signalr complete series] Net6 Zhongshi signalr communication
Notes on redisson distributed lock usage
WPF of open source project hero alliance
Lianyirong (passed)
Implementation of publish and subscribe mode ----- hand tearing JS series
OpenGL Chapter 11 multiple light sources
JS the most commonly used sorting - hand tearing JS series
JS to realize coritization
Thinkphp3.2.3 deserialization using chain analysis
RT thread test
Parameter transfer format when the parameter of PostgreSQL function is a user-defined type
J. Balanced Tree
Jscpcp L. collecting diamonds (thinking)
手工测试转不了自动化测试,缺的是什么?
How PTP helps several major operators meet 5g timing requirements
Promise use
人与人的一些不同
SSL interaction process