简单服务器实现

利用系统提供的API和库函数,搭建一个简单的服务器,打印从客户端收到的消息在终端。



/*************************************************************************
	> File Name: server.c
	> Author: Pompey Wong
	> FUNCTION: 
	> Created Time: Mon 02 Jul 2018 10:16:42 AM CST
 ************************************************************************/

#include 
#include           /* See NOTES */
#include 
#include 
#include 
#include 
#include 
#include 
 

int main()
{
	struct sockaddr_in addr;
	int ret,clientfd;
	char buf[32] = {0};
	int sockfd = socket(PF_INET,SOCK_STREAM,0);    //socket创建一个软端口
	if(-1 == sockfd)
	{
		perror("socket");
		exit(-1);
	}
	
	addr.sin_family = PF_INET;
	addr.sin_port = htons(6666);
	addr.sin_addr.s_addr = inet_addr("0");
	
	ret = bind(sockfd,(struct sockaddr *)&addr,sizeof(addr));  //将软端口和硬件绑定
	if(-1 == ret)
	{
		perror("bind");
		exit(-1);
	}
		
	ret = listen(sockfd,2);  //监听端口,即将端口设置为被动连接方式,最多可以连接2个端口
	if(-1 == ret)
	{
		perror("listen");
		exit(-1);
	}
	
	while(1)
	{
		usleep(10);
		clientfd = accept(sockfd,NULL,NULL);   //若有服务器连接则返回服务器的操作符
		if(-1 == clientfd)
		{
			perror("accept");
			exit(-1);
		}
		else
			printf("connect\n");
		
		bzero(buf,sizeof(buf));
		
		ret = recv(clientfd,buf,sizeof(buf),0);
		if(-1 == ret)
		{
			perror("recv");
			exit(-1);
		}
		else if(0 == recv)
		{
			printf("client quit\n");
			exit(0);
		}
		else
			printf("recv %d bytes,buf is %s\n",ret,buf);
		
	}
	
	close(sockfd);
	close(clientfd);
	return 0;
}

















你可能感兴趣的:(socket,bind)