首页 > 代码库 > linux中select网络通信
linux中select网络通信
//ser.cpp
#include <iostream>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#define IP "127.0.0.1"
#define PORT 8888
using namespace std;
int main()
{
int sockSer,sockCli;
sockaddr_in addrSer,addrCli;
sockSer = socket(AF_INET,SOCK_STREAM,0);
bzero(&addrSer,sizeof(addrSer));
bzero(&addrCli,sizeof(addrSer));
addrSer.sin_family = AF_INET;
addrSer.sin_port = htons(PORT);
addrSer.sin_addr.s_addr = inet_addr(IP);
socklen_t len = sizeof(sockaddr_in);
bind(sockSer,(sockaddr*)&addrSer,len);
listen(sockSer,5);
char clibuff[255];
memset(clibuff,0,sizeof(clibuff));
//////////////////////////////////////////////////////
fd_set Read;
fd_set Write;
static int maxfd = 0;
int sock_set[100];//socket set.
int size = 1;//index
sockCli = accept(sockSer,(sockaddr*)&addrCli,&len);
if(sockCli<0)
{
cout<<sockCli<<endl;
cout<<"accept() error!!!!"<<endl;
close(sockSer);
close(sockCli);
return -1;
}
struct timeval _timeout={3,0};
off_t fd = open("a",O_CREAT|O_RDWR);
while(1)
{
FD_ZERO(&Read);
FD_SET(sockCli,&Read);
FD_ZERO(&Write);
FD_SET(fd,&Write);
maxfd = maxfd>sockCli?maxfd:sockCli;
maxfd = maxfd>fd?maxfd:fd;
select(maxfd+1,&Read,&Write,NULL,&_timeout);
if(FD_ISSET(sockCli,&Read))
{
if(fork()==0)
{
cout<<"return"<<endl;
char buff[255];
memset(buff,0,sizeof(buff));
while(1){
read(sockCli,buff,sizeof(buff));
cout<<buff<<endl;
char str[]="xiaoyanzi";
write(sockCli,str,strlen(str)+1);
}
}
}
if(FD_ISSET(fd,&Write))
{
write(fd,"1234",5);
sleep(1);
}
}
return 0;
}
#include <iostream>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define IP "127.0.0.1"
#define PORT 8888
using namespace std;
int main()
{
int sockCli = socket(AF_INET,SOCK_STREAM,0);
sockaddr_in addrSer;
bzero(&(addrSer),sizeof(addrSer));
addrSer.sin_family = AF_INET;
addrSer.sin_port = htons(PORT);
addrSer.sin_addr.s_addr = inet_addr(IP);
socklen_t len = sizeof(sockaddr_in);
int Ret = connect(sockCli,(sockaddr*)&addrSer,len);
if(Ret != 0)
{
close(sockCli);
return -1;
}
char serbuff[]="liuhuiyan";
char clibuff[255];
while(1)
{
write(sockCli,serbuff,strlen(serbuff)+1);
read(sockCli,clibuff,sizeof(clibuff));
cout<<clibuff<<endl;
sleep(1);
}
return 0;
}
//Makefile
SER=ser
CLI=cli
CC=g++
Status=-g
all:$(CLI) $(SER)
.PHONY:all
$(SER):$(SER).cpp
@$(CC) -o $@ $^ $(Status)
$(CLI):$(CLI).cpp
@$(CC) -o $@ $^ $(Status)
.PHONY:clean
clean:
rm -rf *.o $(SER) $(CLI)
linux中select网络通信
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。