【Linux】pthread与socket高并发程序设计

【Linux多线程服务器程序设计】


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

void *thread_network_echo(void *arg)
{
	int sd = (int) arg;
	int RECV_BUF_SIZE = 2048;
	char recv_buf[RECV_BUF_SIZE];
	int n, nwrote;

	while (1)
	{
		/* read a max of RECV_BUF_SIZE bytes from socket */
		if ((n = recv(sd, recv_buf, RECV_BUF_SIZE, 0)) <= 0)
			break;

		/* break if the recved message = "quit" */
		if (!strncmp(recv_buf, "quit", 4))
			break;

		/* handle request */
		if ((nwrote = send(sd, recv_buf, n, 0)) < 0)
			break;
	}

	/* close connection */
	close(sd);
	pthread_detach(pthread_self());
	return NULL;
}

int main(int argc, char const *argv[])
{
	int sock, new_sd;
	int size;
	struct sockaddr_in address, remote;
	pthread_t thdid;

	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		fprintf(stderr, "create sock failed. \r\n");
		return -1;
	}

	address.sin_family = AF_INET;
	address.sin_port = htons(1234);
	address.sin_addr.s_addr = INADDR_ANY;

	if (bind(sock, (struct sockaddr *) &address, sizeof(address)) < 0)
	{
		fprintf(stderr, "bind failed. \r\n");
		return -2;
	}

	listen(sock, 0);

	size = sizeof(remote);

	while (1)
	{
		if ((new_sd = accept(sock, (struct sockaddr *) &remote, (socklen_t *) &size)) > 0)
		{
			pthread_create(&thdid, NULL, thread_network_echo, (void *) new_sd);
			printf("[%s:%d] connected.\r\n", inet_ntoa(remote.sin_addr),
					ntohs(remote.sin_port));
		}
	}
}


你可能感兴趣的:(Linux)