/************client**********/
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#define PORT 1234
#define SERVER_IP "127.0.0.1"
main()
{
int s;
struct sockaddr_in addr;
char buffer[256];
static int flag = 1;
if((s = socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
exit(1);
}
/*
填写sockaddr_in结构*/
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port=htons(PORT);
addr.sin_addr.s_addr = inet_addr(SERVER_IP);
/* 尝试连线*/
if(connect(s,&addr,sizeof(addr))<0)
{
perror("connect");
exit(1);
}
/* 接收由server端传来的信息*/
recv(s,buffer,sizeof(buffer),0);
printf("%s\n",buffer);
while(1)
{
bzero(buffer,sizeof(buffer));
/* 从标准输入设备取得字符串*/
if (flag == 1)
read(STDIN_FILENO,buffer,sizeof(buffer));
printf("Insert data:%s\n", buffer);
flag = 0;
}
else
{
read(s,buffer,sizeof(buffer));
printf("From sever: %d\n\n", buffer[0]);
}
/*
将字符串传给server端*/
sleep(2);
buffer[0] += 1;
if(write(s,buffer,sizeof(buffer))<0)
{
perror("send");
exit(1);
}
printf("To sever: %d\n", buffer[0]);
}
}
/***************sever*************/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/select.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define PORT 1234
#define MAXSOCKFD 10
void main()
{
int sockfd,newsockfd,is_connected[MAXSOCKFD],fd;
struct sockaddr_in addr;
int addr_len = sizeof(struct sockaddr_in);
fd_set readfds;
char buffer[256];
char msg[ ] ="Welcome to server!";
if ((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
exit(1);
}
bzero(&addr,sizeof(addr));
addr.sin_family =AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
//addr.sin_addr.s_addr = inet_addr(SERVER_IP);
if(bind(sockfd,&addr,sizeof(addr))<0)
{
perror("connect");
exit(1);
}
if(listen(sockfd,3)<0)
{
perror("listen");
exit(1);
}
for(fd=0;fd<MAXSOCKFD;fd++)
is_connected[fd]=0;
while(1)
{
FD_ZERO(&readfds);
FD_SET(sockfd,&readfds);
for(fd=0;fd<MAXSOCKFD;fd++)
{
if(is_connected[fd])
FD_SET(fd,&readfds);
}
/*
阻塞,如果文件描述符没有改变
*/
if(!select(MAXSOCKFD,&readfds,NULL,NULL,NULL))
{
continue;
}
for(fd=0;fd<MAXSOCKFD;fd++)
{
if(FD_ISSET(fd,&readfds))
{
printf("sockfd = %d, fd = %d\n", sockfd, fd);
/*
两个描述符相等时表示有新的客户端连接到达
*/
if(sockfd ==fd)
{
if((newsockfd = accept (sockfd,&addr,&addr_len))<0)
perror("accept");
write(newsockfd,msg,sizeof(msg));
printf("newsockfd = %d\n", newsockfd);
is_connected[newsockfd] =1;
printf("cnnect from %s\n",inet_ntoa(addr.sin_addr));
}
else
{
bzero(buffer,sizeof(buffer));
if(read(fd,buffer,sizeof(buffer))<=0)
{
printf("connect closed.\n");
is_connected[fd]=0;
close(fd);
}
else
{
printf("From client: %d\n",buffer[0]);
if (write(fd, buffer, strlen(buffer)) < 0)
perror("write");
printf("To client: %d\n\n",buffer[0]);
}
}
}
}
}
}