12-20

发布时间:2023年12月20日

#include <myhead.h>
#define SERIP "192.168.125.12"
#define SERPORT 9999
int main(int argc, const char *argv[])
{
	int sfd=-1;
	if((sfd=socket(AF_INET,SOCK_STREAM,0))==-1)
	{
		perror("socket error");
		return -1;
	}
	printf("sfd=%d\n",sfd);
	
	int reuse=1;
	if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
	{
		perror("setsockopt error");
		return -1;
	}
	
	struct sockaddr_in sin;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(SERPORT);
	sin.sin_addr.s_addr=inet_addr(SERIP);
	struct sockaddr_in cin;
	socklen_t socklen=sizeof(cin);

	if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
	{
		perror("bind error");
		return -1;
	}
	printf("bind success\n");

	if(listen(sfd,128)==-1)
	{
		perror("listen error");
		return -1;
	}
	printf("listen success\n");

	int newfd=-1;
	if((newfd=accept(sfd,(struct sockaddr*)&cin,&socklen))==-1)
	{
		perror("connect error");
		return -1;
	}
	printf("connect success\n");
	
	struct pollfd fds[2];
	fds[0].fd=0;
	fds[0].events=POLLIN;

	fds[1].fd=newfd;
	fds[1].events=POLLIN;

	int res=-1;
	char rbuf[128]="";
	while(1)
	{
		res=poll(fds,2,-1);
		if(res<0)
		{
			perror("poll error");
			return -1;
		}
		else if(res==0)
		{
			printf("time out\n");
			return -1;
		}

		if(fds[0].revents==POLLIN)
		{
			bzero(rbuf,sizeof(rbuf));
			fgets(rbuf,sizeof(rbuf),stdin);
			rbuf[strlen(rbuf)-1]=0;
			send(newfd,rbuf,sizeof(rbuf),0);
		}
		if(fds[1].revents==POLLIN)
		{
			bzero(rbuf,sizeof(rbuf));
			int res=recvfrom(newfd,rbuf,sizeof(rbuf),0,(struct sockaddr*)&cin,&socklen);
			if(res==0)
			{
				printf("[%s:%d]已下线\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
				break;
			}
			printf("[%s:%d]:%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),rbuf);
		}
	}
	close(newfd);
	close(sfd);
	return 0;
}

文章来源:https://blog.csdn.net/limbojy0721/article/details/135116242
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。