当前位置:网站首页>Socket programming II: using Select
Socket programming II: using Select
2022-07-27 06:43:00 【Mr FF】
tcp_server.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
// socket
int listenFd = socket(AF_INET, SOCK_STREAM, 0);
if (listenFd < 0) {
perror("socket");
exit(1);
}
struct sockaddr_in serverAddr;
bzero(&serverAddr, sizeof(struct sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[2]));
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
// bind
if (bind(listenFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
perror("bind");
exit(2);
}
// listen
if (listen(listenFd, 30) < 0) {
perror("listen");
exit(3);
}
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
while (1) {
int connFd = accept(listenFd, (struct sockaddr*)&clientAddr, &clientAddrLen);
if (connFd < 0) {
perror("accept");
close(listenFd);
exit(4);
}
// use select.
char buf[1024] = {0};
fd_set readFds;
fd_set exceptionFds;
FD_ZERO(&readFds);
FD_ZERO(&exceptionFds);
while (1) {
// bind the connFd and fd_set.
FD_SET(connFd, &readFds);
FD_SET(connFd, &exceptionFds);
int ret = select(connFd + 1, &readFds, NULL, &exceptionFds, NULL);
if (ret < 0) {
perror("select");
return -1;
}
if (FD_ISSET(connFd, &readFds)) { //read event.
read(connFd, buf, 1024);
printf("recv:%s\n", buf);
}
if (FD_ISSET(connFd, &exceptionFds)) { //exception event.
}
}
close(connFd);
}
close(listenFd);
return 0;
}边栏推荐
猜你喜欢
随机推荐
C language - file operation
Basic knowledge of English: Rules for the use of non predicates Part 1
GoLand 编写go程序
Shell脚本编写格式
Packaging of logging logs
Vscode solves the problem of using stuck ipynb files when running
Shell script one click configuration lamp
ArcGIS for JS API (1) get all field names of FeatureLayer
源码编译安装LNMP和DISCUZ论坛
源码编译安装LAMP和DISCUZ论坛
网络故障排查:Ping和Tracert命令
2022年全球最具技术实力的的智能合约安全审计公司推荐
Compatibility test knowledge points
云原生运行环境搭建
Shell语句判断练习题
darknet-yolov3、yolo-fastect使用rtx30系显卡cuda环境在win10平台编译与训练的相关问题
Concept and principle of DHCP
Function call of shell script
Interface test process and interview questions
Solve the problems of CONDA install stop and interruption









