客户端代码:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
int main()
{
int fd=open("./file",O_CREAT | O_RDWR,0666);
if(fd<0){
perror("open");
return 0;
}
close(1);
int new_fd=dup2(fd,1);
char buf[1024];
while(1){
memset(buf,'\0',sizeof(buf));
fgets(buf,sizeof(buf),stdin);
if(strncmp("quit",buf,4)==0)
break;
printf("%s",buf);
fflush(stdout);
}
close(new_fd);
}
服务器端代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string.h>
int array_fds[1024];
static void Usage(const char *proc)
{
printf("Usage: %s [local_ip] [local_port]\n",proc);
}
int startup(char *_ip,short _port)
{
int sock=socket(AF_INET,SOCK_STREAM,0);
if(sock<0){
perror("socket");
exit(2);
}
int flag=1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port=htons(_port);
local.sin_addr.s_addr=inet_addr(_ip);
if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0){
perror("bind");
exit(3);
}
if(listen(sock,10)<0){
perror("listen");
exit(4);
}
return sock;
}
int main(int argc,char *argv[])
{
if(argc!=3){
Usage(argv[0]);
return 0;
}
int listenSock=startup(argv[1],atoi(argv[2]));
int maxfd=0;
fd_set rfds;
int array_size=sizeof(array_fds)/sizeof(array_fds[0]);
array_fds[0]=listenSock;
int i=1;
for(;i<array_size;i++){
array_fds[i]=-1;
}
while(1){
struct timeval _timeout={0,0};
FD_ZERO(&rfds);
maxfd=-1;
for(i=0;i<array_size;++i){
if(array_fds[i]>0){
FD_SET(array_fds[i],&rfds);
if(array_fds[i]>maxfd)
maxfd=array_fds[i];
}
}
switch(select(maxfd+1,&rfds,NULL,NULL,NULL)){
case 0:
printf("timeout...\n");
break;
case -1:
perror("select");
break;
default:
{
int j=0;
for(;j<array_size;j++){
if(array_fds[j]<0)
continue;
if(j==0&&FD_ISSET(array_fds[j],&rfds)){
struct sockaddr_in client;
socklen_t len=sizeof(client);
int new_fd=accept(array_fds[j],\
(struct sockaddr*)&client,&len);
if(new_fd<0){
perror("accept");
continue;
}else{
printf("get a new client:(%s:%d)\n",\
inet_ntoa(client.sin_addr),\
ntohs(client.sin_port));
int k=1;
for(;k<array_size;++k){
if(array_fds[k] < 0 )
{
array_fds[k] = new_fd;
break;
}
}
if(k==array_size){
close(new_fd);
}
}
}//fi
else if(j!=0&&FD_ISSET(array_fds[j],&rfds)){
char buf[10240];
size_t s=read(array_fds[j],buf,sizeof(buf)-1);
if(s>0){
buf[s]=0;
printf("client say :%s\n",buf);
}else if(s==0){
printf("client quit!\n");
close(array_fds[j]);
array_fds[j]=-1;
}else{
perror("read");
close(array_fds[j]);
array_fds[j]=-1;
}
}
else{}
}
}
break;
}
}
return 0;
}