当前位置:网站首页>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
边栏推荐
- More dragon lizard self-developed features! Production available Anolis OS 8.6 officially released
- IO stream_ recursion
- IndexSearch
- 声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏
- Delete duplicates in an ordered array ii[double pointers -- unified in multiple cases]
- Etcd教程 — 第九章 Etcd之实现分布式锁
- 【牛客网刷题系列 之 Verilog快速入门】~ 位拆分与运算
- Arcmap操作系列:80平面转经纬度84
- 搬运两个负载均衡的笔记,日后省的找
- POJ Project Summer
猜你喜欢

赛芯电子冲刺科创板:拟募资6.2亿 实控人谭健为美国籍
![[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection](/img/c2/d6760826b81589781574aebff61f9a.png)
[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection

MC Instruction Decoder

Symantec electronic sprint technology innovation board: Tan Jian, the actual controller, is an American who plans to raise 620million yuan

MySQL transaction / lock / log summary

牛客网:乘积为正数的最长连续子数组
![Delete duplicates in an ordered array ii[double pointers -- unified in multiple cases]](/img/e2/cadfdbe476a86cb2d72c1ae0160a4a.png)
Delete duplicates in an ordered array ii[double pointers -- unified in multiple cases]

【活动报名】探秘元宇宙,就差你了!7月2号我在深圳现场等你!

TCP Socket与TCP 连接

Mathematical modeling for war preparation 34-bp neural network prediction 2
随机推荐
microblaze 串口学习·2
BC1.2 PD协议
HMS Core音频编辑服务3D音频技术,助力打造沉浸式听觉盛宴
声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏
Asp. NETCORE uses cache and AOP to prevent repeated commit
TCP Socket与TCP 连接
Good partner for cloud skill improvement, senior brother cloud of Amazon officially opened today
药品管理系统加数据库,一夜做完,加报告
register_ Chrdev and CDEV_ init cdev_ Add usage differences
24:第三章:开发通行证服务:7:自定义异常(来表征程序中出现的错误);创建GraceExceptionHandler来全局统一处理异常(根据异常信息,构建对应的API统一返回对象的,JSON数据);
Exception class_ Log frame
Halcon knowledge: regional topics [07]
Etcd教程 — 第八章 Etcd之Compact、Watch和Lease API
I 用c I 实现“栈”
mysql8报错:ERROR 1410 (42000): You are not allowed to create a user with GRANT解决办法
The image variables in the Halcon variable window are not displayed, and it is useless to restart the software and the computer
AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
Yunhe enmo won the bid for Oracle maintenance project of Tianjin Binhai rural commercial bank in 2022-2023
搬运两个负载均衡的笔记,日后省的找
Mysql8 error: error 1410 (42000): you are not allowed to create a user with grant solution