//服务器端代码..........
#include
#include
#include
#include
#include
#define MYPORT 8000
#define BACKLOG 10
int main(void)
{
int sockfd,con_fd,numbytes,ret,pid;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
int lis;
char buf[256];
socketing:
//creat socket.
sockfd=socket(AF_INET,SOCK_STREAM,0);
if (sockfd==-1)
{
printf("failed when creating\n");
exit(-1);
}
//binding socket.
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(MYPORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
ret=bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr));
if (ret==-1)
{
printf("failed when binding\n");
exit(-1);
}
//listen.
if (listen(sockfd,BACKLOG)==-1)
{
printf("failed when listening\n");
exit(-1);
}
printf("server listening...wait for connect...\n");
while (1)
{
sin_size=sizeof(struct sockaddr);
con_fd=accept(sockfd,(struct sockaddr*)&their_addr,&sin_size);
if (con_fd<0)
{
printf("failed when accepting\n");
exit(-1);
}
//recv a string from client and print the string.
if (recv(con_fd,buf,sizeof(buf),0)==-1)
{
printf("failed when receiving the string\n");
exit(-1);
}
printf(" received form client...%s\n",buf);
//send the buf string to client and print it.
if (send(con_fd,&buf,sizeof(buf),0)==-1)
{
printf("failed when sending the string");
exit(-1);
}
printf(" send to client...%s\n",buf);
close(con_fd);
}
close(sockfd);
exit(0);
}
|