#include<th.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"__%d__",__LINE__);\
perror(msg);\
}while(0)
#define PORT 7777
#define IP "192.168.115.125"
int main(int argc, const char *argv[])
{
int sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd < 0)
{
ERR_MSG("socket error");
return -1;
}
printf("socket success\n");
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin)) < 0)
{
ERR_MSG("bind error");
return -1;
}
printf("bind success\n");
if(listen(sfd,128) < 0)
{
ERR_MSG("listen error");
return -1;
}
printf("listen success\n");
//创建一个读集合
fd_set readfds,tempfds;
//清空集合
FD_ZERO(&readfds);
//添加需要监测的文件描述符
FD_SET(0,&readfds);
FD_SET(sfd,&readfds);
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
char buf[213] = "";
int newfd = -1;
int maxfd = sfd;
int s_res = -1;
ssize_t res = -1;
struct sockaddr_in saveCin[1024];
while(1)
{
tempfds = readfds;
s_res = select(maxfd + 1,&tempfds,NULL,NULL,NULL);
if(s_res < 0)
{
ERR_MSG("select error");
return -1;
}
else if(0 == s_res)
{
printf("time out\n");
break;
}
for(int i = 0; i <= maxfd; i++)
{
if(FD_ISSET(i,&tempfds) == 0)
continue;
if(0 == i)
{
printf("触发键盘输入事件\n");
bzero(buf,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) - 1] = '\0';
printf(": %s\n",buf);
}
else if(sfd == i)
{
printf("触发客户端连接事件\n");
newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
if(newfd < 0)
{
ERR_MSG("accept error");
return -1;
}
printf("[%s:%d]客户端连接成功 newfd = %d\n",\
inet_ntoa(cin.sin_addr),\
ntohs(cin.sin_port),newfd);
saveCin[newfd] = cin;
FD_SET(newfd,&readfds);
maxfd = maxfd > newfd ? maxfd : newfd;
}
else
{
printf("触发客户端交互事件\n");
//清空字符串
bzero(buf,sizeof(buf));
//接收
res = recv(i,buf,sizeof(buf),0);
if(res < 0)
{
ERR_MSG("recv error");
return -1;
}
else if(0 == res)
{
printf("[%s:%d]客户端下线 newfd = %d\n",\
inet_ntoa(cin.sin_addr),\
ntohs(cin.sin_port),i);
close(i);
FD_CLR(i,&readfds);
while(FD_ISSET(maxfd,&readfds) == 0 && maxfd-- >= 0);
continue;
}
printf("[%s:%d] newfd = %d : %s\n",\
inet_ntoa(cin.sin_addr),\
ntohs(cin.sin_port),i,buf);
//发送
strcat(buf,">_<");
if(send(i,buf,sizeof(buf),0) < 0)
{
ERR_MSG("send error");
return -1;
}
printf("send success\n");
}
}
}
//关闭文件描述符
if(close(sfd) < 0)
{
ERR_MSG("close error");
return -1;
}
return 0;
}
ubuntu
DAY39
最新推荐文章于 2024-08-16 23:44:41 发布