www.pudn.com > tcp.zip > test_server.c, change:2001-02-14,size:1656b


/* 
  一个使用tcp.c的服务器例子(hp-unix):接收不定长字符串 
  by lgd/paladin, http://www.programsalon.com   
*/ 
#include <stdio.h> 
#include <stdlib.h> 
#include <signal.h> 
 
#include "tcp.h" 
 
void app_exit(int sig); 
int g_sd_bind =-1; 
 
void main() 
{ 
	int port =1234; 
		 
	sigset(SIGCHLD, SIG_IGN); 
	sigset(SIGINT, app_exit); 
	sigset(SIGTERM, app_exit); 
	sigset(SIGQUIT, app_exit); 
	sigset(SIGKILL, app_exit); 
 
	if((g_sd_bind =tcp_bind(port)) <0) 
	{ 
		printf("bind port %d failed!\n"); 
		return; 
	} 
	int sd; 
	int buf_len; 
	char *buf; 
	while(1) 
	{ 
		while((sd =tcp_accept(g_sd_bind, 5)) <0) sleep(1); 
		switch(fork()) 
		{ 
			case 0: // child process 
				if(tcp_recv(sd, buf_len, sizeof(buf_len), 10) !=sizeof(buf_len)) 
				{ 
					printf("tcp_recv failed!\n"); 
					tcp_close(sd); 
					tcp_close(g_sd_bind); 
					exit(-1); 
				} 
				buf_len =tcp_ntohl(buf_len);   //转换整数字节顺序由网络顺序转换为本地机顺序 
				if((buf =(char *)malloc(buf_len+1)) ==NULL) 
				{ 
					printf("malloc buf failed!\n"); 
					tcp_close(sd); 
					tcp_close(g_sd_bind); 
					exit(-1); 
				} 
				memset(buf, 0, buf_len+1); 
				if(tcp_recv(sd, buf, buf_len, 10) !=buf_len) 
				{ 
					printf("tcp_recv buf failed!\n"); 
					tcp_close(sd); 
					tcp_close(g_sd_bind); 
					exit(-1); 
				} 
				tcp_close(sd); 
				tcp_close(g_sd_bind); 
				printf("recved buf is: %s\n", buf); 
				free(buf); 
				exit(0); 
			case -1: 
				printf("fork child process failed!\n"); 
		} 
		tcp_close(sd); 
	} 
} 
 
void app_exit(int sig) 
{ 
	printf("exit...\n"); 
	if(g_sd_bind >0) tcp_close(g_sd_bind); 
	g_sd_bind =-1; 
	tcp_exit(); 
	exit(0); 
}