#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 1234
#define BACKLOG 10
#define MAX_CONNECTED_NO 10
#define MAXDATASIZE 100
int main()
{
struct sockaddr_in server_addr,client_addr;
int sin_size,recvbytes,flags;
int sockfd,client_fd;
char buf[MAXDATASIZE];
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
perror("socket error");
exit(1);
}
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(PORT);
server_addr.sin_addr.s_addr=INADDR_ANY;
bzero(&(server_addr.sin_zero),8);
if(bind(sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1){
perror("bind");
exit(1);
}
printf("bind success!\n");
if(listen(sockfd,BACKLOG)==-1){
perror("listen error");
exit(1);
}
if((flags=fcntl(sockfd,F_SETFL,0))<0)
perror("fcntl F_SETFL");
flags|=O_NONBLOCK;
if(fcntl(sockfd,F_SETFL,flags)<0)
perror("fcntl");
while(1){
sin_size=sizeof(struct sockaddr_in);
if((client_fd=accept(sockfd,(struct sockaddr*)&client_addr,&sin_size))==-1){
perror("accept");
exit(1);
}
if((recvbytes=recv(client_fd,buf,MAXDATASIZE,0))==-1){
perror("recv error");
exit(1);
}
if(read(client_fd,buf,MAXDATASIZE)<0){
perror("read error");
exit(1);
}
close(client_fd);
exit(1);