关于IO多路复用的思维导图

使用select实现TCP客户端并发运行的示例

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>

#define SER_PORT 8888//服务器端口
#define SER_IP "192.168.125.132"//服务器IP
#define CLI_PORT 6666//服务器端口
#define CLI_IP "192.168.125.132"//服务器IP


int main(int argc, const char *argv[])
{
	int cfd=socket(AF_INET,SOCK_STREAM,0);
	if(cfd==-1){
		perror("socket error\n");
		return -1;
	}
	printf("cfd=%d\n",cfd);

	struct sockaddr_in cin;
	cin.sin_family=AF_INET;
	cin.sin_port=htons(CLI_PORT);
	cin.sin_addr.s_addr=inet_addr(CLI_IP);

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

	struct sockaddr_in sin;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(SER_PORT);
	sin.sin_addr.s_addr=inet_addr(SER_IP);

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

	fd_set readfds,tempfds;
	FD_ZERO(&readfds);
	FD_SET(cfd,&readfds);
	FD_SET(0,&readfds);

	char wbuf[128]="";
	char rbuf[128]="";
	while(1){
		tempfds=readfds;

		int res=select(cfd+1,&tempfds,NULL,NULL,NULL);
		if(res==-1){
			perror("select error");
			return -1;
		}else if(res==0){
			printf("time out");
			return -1;
		}

		if(FD_ISSET(cfd,&tempfds)){

			bzero(rbuf,sizeof(rbuf));
			recv(cfd,rbuf,sizeof(rbuf),0);
			printf("消息为:%s\n",rbuf);
		}
		if(FD_ISSET(0,&tempfds)){
			fgets(wbuf,sizeof(wbuf),stdin);
			wbuf[strlen(wbuf)-1]=0;
			send(cfd,wbuf,strlen(wbuf),0);
			printf("发送成功\n");
		}
	}

	close(cfd);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值