#include
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:",__LINE__);\
perror(msg);\
}while(0)
#define PORT 8888
#define IP "192.168.114.79"
int main(int argc, const char *argv[])
{
//创建流式套接字 socket
int sfd = socket(AF_INET, SOCK_STREAM,0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("socket create success sfd = %d\n",sfd);
//允许端口快速被复用
int reuse =1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR,&reuse,sizeof(reuse))<0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速被复用成功\n");
//填充地址信息结构体给bind函数绑定,
//真实的地址信息结构体根据地址族指定 AF_INET:man 7 ip
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
//绑定服务器的地址信息--->必须绑定 bind
if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
//将套接字设置为被动监听状态 listen
if(listen(sfd, 128) < 0)
{
ERR_MSG("listen");
return -1;
}printf("listen success\n");
//创建一个读集合
fd_set readfds, tempfds;
//清空集合
FD_ZERO(&readfds);
//将需要检测的文件描述符添加到集合中
FD_SET(0,&readfds);
FD_SET(sfd,&readfds);
int maxfd = sfd;
int s_res = -1;
ssize_t res = -1;
char buf[128] = "";
int newfd = -1;
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
while(1)
{
tempfds = readfds;
//执行IO多路服用函数
s_res = select(maxfd+1,&tempfds, NULL,NULL,NULL);
if(s_res < 0)
{
ERR_MSG("setele");
return -1;
}
else if(0 == s_res)
{
printf("time out,,\n");
break;
}
printf("__%d__\n",__LINE__);
if(FD_ISSET(0,&tempfds))
{
printf("触发键盘输入事件\n");
bzero(buf,sizeof(buf));
fgets(buf, sizeof(buf),stdin);
buf[strlen(buf)-1] = 0;
printf(": %s\n",buf);
}
if(FD_ISSET(sfd,&tempfds))
{
printf("触发客户端连接事件\n");
newfd = accept(sfd, (struct sockaddr*)&cin,&addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s:%d]客户端连接成功 newfd=%d\n",\
inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);
//将newfd添加到集合中
FD_SET(newfd, &readfds);
maxfd = maxfd>newfd ? maxfd : newfd;
}
for(int i=4; i<=maxfd; i++)
{
if(FD_ISSET(i,&tempfds))
{
printf("触发客户端交互事件\n");
bzero(buf, sizeof(buf));
//接收
res = recv(i, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
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);
continue;
}
printf("[%s:%d] newfd=%d\n :%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");
return -1;
}
printf("send success\n");
}
}
}
if(close(sfd) < 0)
{
ERR_MSG("close");
return -1;
}
return 0;
}