poll服務器

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define array_size 1024
int startup(const char* _ip, int _port)
{
	int sock = socket(AF_INET, SOCK_STREAM, 0);
	if(sock < 0)
	{
		perror("create sock is fail");
		return 2;
	}

	struct sockaddr_in peer;
	peer.sin_family = AF_INET;
	peer.sin_port = htons(_port);
	peer.sin_addr.s_addr = inet_addr(_ip);

	int opt = 1;
	if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1)
	{
		perror("setsockopt");
		return 3;
	}

	if(bind(sock, (struct sockaddr*)&peer, sizeof(peer)) < 0)
	{
		perror("bind");
		return 4;
	}

	if(listen(sock, 10) < 0)
	{
		perror("listen");
		return 5;
	}
	
	return sock;

}

static void Usage(const char* proc)
{
	printf("%s[ip][port]\n", proc);
}

int main(int argc, char *argv[])
{
	if(argc != 3)
	{
		Usage(argv[0]);
		return 1;
	}

	int listensock = startup(argv[1], atoi(argv[2]));

	struct  pollfd array_fds[1024];
	array_fds[0].fd = listensock;
	array_fds[0].events = POLLIN;

	int i = 1;
	for(; i < array_size; i++)
	{
		array_fds[i].fd = -1;
	}

	int _timeout = 1000;
	while(1)
	{
		switch(poll(array_fds, 1024, _timeout))
		{
			case 0:
				printf("timeout......");
				break;
			case -1:
				perror("poll");
				break;
			default:
				{
					int j = 0;
					for(; j < array_size; j++)
					{
						if(j == 0 && array_fds[0].revents & POLLIN)
						{
							struct sockaddr_in client;
							socklen_t len = sizeof(client);
							int new_fd = accept(array_fds[j].fd, (struct sockaddr*)&client, &len);
							if(new_fd < 0)
							{
								perror("new_fd: accept");
								continue;
							}else
							{
								printf("connect is success! ip: %s port: %d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
								
								int k = 1;
								for(; k < array_size; k++)
								{
									if(array_fds[k].fd < 0)
									{
										array_fds[k].fd = new_fd;
										array_fds[k].events = POLLIN;
										break;
									}
								}
								if(k == array_size)
								{
									printf("連接超出最大限度");
									return;
								}
							}
						}
						else if(j != 0 && array_fds[j].revents & POLLIN)
						{
							char buf[1024];
							memset(buf, 0, sizeof(buf));
							ssize_t s = read(array_fds[j].fd, buf, sizeof(buf)-1);
							if(s > 0)
							{
								buf[s-1] = '\0';
								printf("client say# %s\n", buf);
								array_fds[j].events = POLLOUT;
							}else if(s == 0)
							{
								printf("client is quit!");
								close(array_fds[j].fd);
								array_fds[j].fd = -1;
							}else
							{
								perror("read");
								close(array_fds[j].fd);
								array_fds[j].fd = -1;
							}
						}
						else if(j != 0 && array_fds[j].revents & POLLOUT)
						{
							const char* msg = "HTTP/1.1 200 OK \r\n\r\n

hello poll

"; write(array_fds[j].fd, msg, strlen(msg)); close(array_fds[j].fd); array_fds[j].fd = -1; } } } break; } } return 0; }

發佈了50 篇原創文章 · 獲贊 20 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章