当前位置:网站首页>TCP socket and TCP connection
TCP socket and TCP connection
2022-06-30 16:51:00 【Potato, watermelon and sesame】
One . TCP Socket and TCP Connect
- tcp socket
tcp socket It indicates the process of a host , yes tcp An instance at one end of the connection .socket It's not a connection , It just means one end . from IP and port constitute . - tcp Connect
tcp The connection is made by processes on two hosts socket The connection constitutes .
1.1 tcp Server side
To establish tcp Connect , Play the role server The process at one end of the role needs :
- adopt
socket()The system calls to create a new socket( It just creates one locally tcp scoket, It doesn't make a connection );
sockfd = socket(AF_INET, SOCK_STREAM, 0);// Just create a local one socket Entity , Get one fd, But not with any ports and IP binding ;
///* address family, AF_xxx, Protocol cluster , What we use here is INET Address family , It's through TCP/IP The agreement supports Internet Address family */
//SOCK_STREAM That's right BSD The socket type is stream (Stream), This socket provides reliable two-way sequential data flow , It can ensure that data will not be lost during transmission 、 Destroy or reappear . Stream socket pass INET Address family TCP Protocol implementation .
//http://www.javashuo.com/article/p-cftecbee-te.html- For new socket binding IP and port.
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
// Create the socket Entity ( from sockfd characterization ), And IP:port binding . Bound socket Can be used later .among serv_addr The structure contains IP and port Information .
- adopt
listen()System call listening connection
listen(sockfd,5);// The server starts listening , At most, it can be compared with 5 Client setup tcp Connect .
//int listen(int sockfd, int backlog);
// The second parameter backlog In order to establish a good connection, it is in ESTABLISHED The length of the queue for status .backlog The maximum of 128(linux The original description is as follows ):If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn, then it is silently truncated to that value; the default value in this file is 128. In kernels before 2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.
//https://blog.csdn.net/u022812849/article/details/109737020- adopt
accept()System call receive connection
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)
here newsockfd It's through accept() The system calls the new socket File descriptor . When server Listen for connection requests , We use this new product socket With the remote client Of socket Communications .
server.c Core code ( Multi process version , Each process handles one client The connection of )
while (1) {
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr, &clilen);// from accept Take an established... From the queue tcp Connect
if (newsockfd < 0)
error("ERROR on accept");
pid = fork(); // Child processes handle connections
if (pid < 0)
error("ERROR on fork");
if (pid == 0) {
close(sockfd);
dostuff(newsockfd);
exit(0);
}
else close(newsockfd);
} server.c Is a multi process version of tcp server, When there is a new request , Use fork() The system call generates a new process to process the connection request :
You can also use multithreading to process requests , When there is a new request , Use pthread_create() call , Generate a new thread . Detailed code reference here .
In fact, the most effective way to handle multiple requests is to use the system epoll, Through the event notification mechanism ,non-blocking Process requests in a timely manner . Detailed code reference here
1.2 Tcp client
In order to establish tcp Connect ,tcp client Did the following things :
- newly build socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);- By system call connect(), With the remote server monitor socket Initiate connection request .
connect(sockfd,&serv_addr,sizeof(serv_addr))
- After successful connection , You can create a new socket in read() and write() To achieve communication .
n = write(sockfd,buffer,strlen(buffer));
n = read(sockfd,buffer,255);Two . socket file
In everything is documented Unix-like In the system , Process produced socket adopt socket Documents to show , The process passes to socket File read / write content realizes message transmission .
stay Linux In the system , Usually socket The file in /proc/pid/fd Under the document . Through the top server.c and client.c Practice a , Take a peek at the corresponding socket file .
To compile the first server.c and client.c
gcc server.c -o server
gcc client.c -o clientRun locally 30000 On port :
server 30000
use lsof perhaps netstat see server process ID
according to pid(17009), Go to the catalog /proc/17009/fd Check out :
among socket:[1293853508] That is socket file .
function client, Connect to server On .
client localhost 30000
Don't send messages yet , Keep connected . And then through lsof Command view 30000 port :
Look at the picture NAME This column , among
- first line ,*:30000 yes server To monitor socket file name
- The second line ,localhost:57684->localhost:30000 (ESTABLISHED) yes client End socket file name
- The third line ,localhost:30000->localhost:57684 (ESTABLISHED) yes server intention client End of the request to create a new socket, Responsible for and client signal communication
3、 ... and . Unix Domain socket
As mentioned above socket yes internet domain socket, Used for communication between processes of different hosts . stay Unix in , Process communication between native computers usually uses another method socket( Unix domain socket). newly build Unix domain socket The connection and internet domain socket The connection is almost the same , The only difference is socket() When the system calls, it passes in socket type It's just different .
sockfd = socket(AF_UNIX,SOCK_STREAM,0)Notice the AF_UNIX and above AF_INET difference .
Unix socket server Program userver.c
Unix socket client Program uclient.c
compile :
gcc userver.c -o userver
gcc uclientj.c -o uclient
userver Receive a parameter , Used to create socket file , The parameter is socket Name of file . For example, use /tmp/usfd As socket file .
userver /tmp/usfd
Check out the newly produced socket file :
ls -l /tmp/usfd
Of the document mode string First character of s That means this is one socket file .
Link to the original text :https://blog.csdn.net/bdss58/article/details/77929685
边栏推荐
- MySQL8.0开启远程连接权限的方法步骤
- Siyuan notes: can you provide shortcut keys for folding all titles on the page?
- POJ Project Summer
- In order to make remote work unaffected, I wrote an internal chat room | community essay
- 【机器学习】K-means聚类分析
- Dart: string replace related methods to solve replacement characters
- Eight basic sorting (detailed explanation)
- 云和恩墨中标天津滨海农村商业银行2022-2023年度Oracle维保项目
- Bc1.2 PD protocol
- Niuke: how many different binary search trees are there
猜你喜欢

深度学习——(2)几种常见的损失函数

Rong Lianyun launched rphone based on Tongxin UOS to create a new ecology of localization contact center

腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?

更多龙蜥自研特性!生产可用的 Anolis OS 8.6 正式发布

Mathematical modeling for war preparation 35 time series prediction model

安全帽佩戴检测算法研究
Two methods for MySQL to open remote connection permission

抖快B为啥做不好综艺

Hundreds of lines of code to implement a JSON parser
MySQL开放远程连接权限的两种方法
随机推荐
Niuke network: longest continuous subarray with positive product
Simpleitk encountered an ITK only supports orthonormal direction cosines error while reading NII
招标公告:2022年台州联通Oracle一体机和数据库维保服务项目
Mathematical modeling for war preparation 33- grey prediction model 2
BC1.2 PD协议
MySQL transaction / lock / log summary
simpleITK读取nii遇到ITK only supports orthonormal direction cosines的错误
Bidding announcement: Taizhou Unicom Oracle all in one machine and database maintenance service project in 2022
八大基本排序(详解)
牛客网:有多少个不同的二叉搜索树
24:第三章:开发通行证服务:7:自定义异常(来表征程序中出现的错误);创建GraceExceptionHandler来全局统一处理异常(根据异常信息,构建对应的API统一返回对象的,JSON数据);
The inspiration from infant cognitive learning may be the key to the next generation of unsupervised machine learning
牛客网:最小花费爬楼梯
Mathematical modeling for war preparation 35 time series prediction model
新茶饮“死去活来”,供应商却“盆满钵满”?
9:第三章:电商工程分析:4:【通用模块】;(待写……)
RTP sending PS stream zero copy scheme
Rong Lianyun launched rphone based on Tongxin UOS to create a new ecology of localization contact center
[machine learning] K-means clustering analysis
Hologres shared cluster helps Taobao subscribe to the extreme refined operation