当前位置:网站首页>TCP Socket与TCP 连接
TCP Socket与TCP 连接
2022-06-30 15:47:00 【土豆西瓜大芝麻】
一. TCP Socket和TCP连接
- tcp socket
tcp socket 是标示了一台主机的进程,是tcp连接中一端的实例。socket不是连接,只是表示了其中一端。由IP和port构成。 - tcp 连接
tcp连接由两台主机上的进程的socket连接构成。
1.1 tcp 服务端
为建立tcp连接,扮演server角色的一端进程需要:
- 通过
socket()系统调用新建一个socket(只是它本地创建一个tcp scoket,并不能构成一个连接);
sockfd = socket(AF_INET, SOCK_STREAM, 0);//只是创建本地的一个socket实体,得到一个fd,但并没有和任何端口以及IP 绑定;
///* address family, AF_xxx,协议簇,这里使用的是INET地址族,它是通过 TCP/IP 协议支持的 Internet 地址族*/
//SOCK_STREAM 说的是BSD 套接字类型是流(Stream),这种套接字提供了可靠的双向顺序数据流,可保证数据不会在传输过程中丢失、破坏或重复出现。流套接字通过 INET 地址族的 TCP 协议实现。
//http://www.javashuo.com/article/p-cftecbee-te.html- 给新建的socket绑定IP和port。
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
//将前面创建的socket实体(由sockfd表征),与IP:port绑定。绑定好的socket才能在后面使用。其中serv_addr结构体内包含了IP和port信息。
- 通过
listen()系统调用监听连接
listen(sockfd,5);//服务端开始监听,最多能与5个客户端建立tcp连接。
//int listen(int sockfd, int backlog);
//第二个参数backlog为建立好连接处于ESTABLISHED状态的队列的长度。backlog的最大值128(linux原文描述如下):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- 通过
accept()系统调用接收连接
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)
这里newsockfd是通过accept()系统调用新建的socket文件描述符。当server监听到连接请求,便用这个新生产的socket与远程client的socket通讯。
server.c核心代码(多进程版,每个进程处理一个client的连接)
while (1) {
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr, &clilen);//从accept队列中取出一个已经建立的tcp连接
if (newsockfd < 0)
error("ERROR on accept");
pid = fork(); // 子进程处理连接
if (pid < 0)
error("ERROR on fork");
if (pid == 0) {
close(sockfd);
dostuff(newsockfd);
exit(0);
}
else close(newsockfd);
} server.c是一个多进程版本的tcp server,当有新的请求时,使用fork()系统调用产生新进程来处理连接请求:
其实也可以用多线程来处理请求,当有新的请求时,使用pthread_create()调用,产生新线程。详细代码参考 这里。
其实最有效当处理多请求当手段是使用系统epoll,通过事件通知机制,non-blocking地处理请求。详细代码参考这里
1.2 Tcp 客户端
为了建立tcp连接,tcp client 做了下面这些事儿:
- 新建socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);- 通过系统调用connect(),与远程server监听socket发起连接请求。
connect(sockfd,&serv_addr,sizeof(serv_addr))
- 连接成功后,便可通过向新建的socket中read()和write()来实现通讯了。
n = write(sockfd,buffer,strlen(buffer));
n = read(sockfd,buffer,255);二. socket 文件
在一切皆文件的Unix-like系统中,进程生产的socket通过socket文件来表示,进程通过向socket文件读写内容实现消息的传递。
在Linux系统中,通常socket文件在/proc/pid/fd文件下。通过上面的server.c和client.c实践一下,窥探一下对应的socket文件。
先编译server.c和client.c
gcc server.c -o server
gcc client.c -o client运行在本地30000端口上:
server 30000
用lsof或者netstat查看server进程ID
根据pid(17009),去目录/proc/17009/fd下查看:
其中socket:[1293853508]便是socket文件。
运行client,连接到server上。
client localhost 30000
先不要发送消息,保持连接。然后通过 lsof命令查看30000端口:
看图中NAME这一列,其中
- 第一行,*:30000是server到监听socket文件名
- 第二行,localhost:57684->localhost:30000 (ESTABLISHED)是client端端socket文件名
- 第三行,localhost:30000->localhost:57684 (ESTABLISHED)是server 端为client端的请求建立的新的socket,负责和client通信
三. Unix Domain socket
上述所说的socket是internet domain socket,用于不同主机之间进程的通信。在Unix中,本机之间进程通信通常用另外一种socket( Unix domain socket)。新建Unix domain socket 连接和 internet domain socket 连接几乎上差不多,唯一的区别就是socket()系统调用时传入socket type 不同而已。
sockfd = socket(AF_UNIX,SOCK_STREAM,0)注意这里的 AF_UNIX 和 上面的AF_INET 区别。
Unix socket server程序userver.c
Unix socket client程序uclient.c
编译:
gcc userver.c -o userver
gcc uclientj.c -o uclient
userver 接收一个参数,用于创建socket文件,参数便是socket文件的名字。比如用 /tmp/usfd作为socket文件。
userver /tmp/usfd
查看一下新生产的socket文件:
ls -l /tmp/usfd
该文件的mode string的第一个字符s表示这是一个socket文件。
原文链接:https://blog.csdn.net/bdss58/article/details/77929685
边栏推荐
- 【Verilog基础】十进制负数的八进制、十六进制表示
- 7 月 2 日邀你来TD Hero 线上发布会
- [Verilog basics] octal and hexadecimal representation of decimal negative numbers
- 招标公告:天津市住房公积金管理中心数据库一体机及数据库软件项目(预算645万)
- Interesting research on mouse pointer interaction
- Interpretation of gaussdb's innovative features: partial result cache accelerates operators by caching intermediate results
- [unity ugui] scrollrect dynamically scales the grid size and automatically locates the middle grid
- MySQL master-slave configuration
- register_chrdev和cdev_init cdev_add用法区别
- MC Instruction Decoder
猜你喜欢

KDD 2022 | how far are we from the general pre training recommendation model? Universal sequence representation learning model unisrec for recommender system

【机器学习】K-means聚类分析

RT-Thread 堆区大小设置
![[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入](/img/c2/d6760826b81589781574aebff61f9a.png)
[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入

安全帽佩戴检测算法研究

ArcMap operation series: 80 plane to latitude and longitude 84
Mysql8 error: error 1410 (42000): you are not allowed to create a user with grant solution

Cesium-1.72 learning (earth model creation online offline tile)

Mathematical modeling for war preparation 33- grey prediction model 2
mysql8报错:ERROR 1410 (42000): You are not allowed to create a user with GRANT解决办法
随机推荐
CVPR 2022 - Tesla AI proposed: generalized pedestrian re recognition based on graph sampling depth metric learning
Niuke.com: minimum cost of climbing stairs
Niuke network: longest continuous subarray with positive product
Siyuan notes: can you provide shortcut keys for folding all titles on the page?
2022新消费半年盘点:行业遇冷,但这九个赛道依然吸金
云化XR,如何助力产业升级
Implementation of Devops in the core field of qunar, the Internet R & D Efficiency
【Verilog基础】十进制负数的八进制、十六进制表示
Li Zexiang, a legendary Chinese professor, is making unicorns in batches
Symantec electronic sprint technology innovation board: Tan Jian, the actual controller, is an American who plans to raise 620million yuan
What is the difference between real-time rendering and pre rendering
Cesium-1.72 learning (earth model creation online offline tile)
[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
备战数学建模36-时间序列模型2
9:第三章:电商工程分析:4:【通用模块】;(待写……)
AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
详解Go语言中for循环,break和continue的使用
After 15 years of working on 21 types of hardware, where is Google?
招标公告:深圳市财政局数据库异地灾备项目
Bidding announcement: Tianjin housing provident fund management center database all-in-one machine and database software project (budget: 6.45 million)