www.pudn.com > vxWorks_Lab.rar > conServer.c


/* conServer.c - demo concurrent TCP server */ 
 
#include "vxWorks.h" 
#include "sockLib.h" 
#include "sys/socket.h" 
#include "netinet/in.h" 
#include "inetLib.h" 
#include "stdio.h" 
#include "stdlib.h" 
#include "ioLib.h" 
#include "taskLib.h" 
#include "string.h" 
#include "conServer.h" 
#include "advTCPLab.h" 
 
#define MAX_MSG_LEN 80 
typedef int SOCK_FD; 
 
/* forward declarations */ 
LOCAL void doRequest(SOCK_FD sock, 
					struct sockaddr_in * pClientAddr); 
LOCAL void error (char * str); 
 
void vxServer 
	( 
	u_short port 
	) 
	{ 
	int clientAddrLength; 
	SOCK_FD sockFd; 
	SOCK_FD newSockFd; 
	struct sockaddr_in * pClientAddr; 
	struct sockaddr_in srvAddr; 
 
	clientAddrLength = sizeof (struct sockaddr_in); 
	if (port == 0) 
		port = SRV_PORT; 
 
	/* Create a socket */ 
	if ((sockFd = socket (PF_INET, SOCK_STREAM, 
		 						IPPROTO_TCP)) < 0) 
		error ("Socket failed"); 
 
	/* 
	 * Bind to a well known address. INADDR_ANY says 
	 * any network interface will do. htonX() 
	 * routines put things in network byte order 
	 */ 
	bzero ((char *)&srvAddr, sizeof(srvAddr)); 
	srvAddr.sin_family = AF_INET; 
	srvAddr.sin_port = htons(port); 
	srvAddr.sin_addr.s_addr = INADDR_ANY; 
	if ( bind (sockFd, (struct sockaddr *) &srvAddr, 
			sizeof(srvAddr)) < 0 ) 
		{ 
		close (sockFd); 
		error ("Bind failed"); 
		} 
 
 
	/* Queue up to 8 requests (max allowed by TCP) */ 
	if ( listen (sockFd, 5) < 0 ) 
		{ 
		close (sockFd); 
		error ("Listen failed"); 
		} 
 
	/* Service requests */ 
	FOREVER 
		{ 
		pClientAddr = 
				malloc (sizeof(struct sockaddr)); 
 
		newSockFd = accept (sockFd, 
						(struct sockaddr *)pClientAddr, 
						&clientAddrLength); 
		if (newSockFd < 0) 
	 		{ 
			close (sockFd); 
	 		error ("Accept failed"); 
	 		} 
 
		taskSpawn ("tSlaveServer", SLAVE_PRIORITY, 0, 
						SLAVE_STACK_SIZE,  
						(FUNCPTR) doRequest, 
						newSockFd,(int) pClientAddr, 
						0,0,0,0,0,0,0,0); 
		} 
 
 	} 
 
 
/**************************************************  
* 
* doRequest - read the clients requests from the 
* socket and honor them. 
* 
*/ 
void doRequest 
	( 
	SOCK_FD sock, 
	struct sockaddr_in * pClientAddr 
	) 
	{ 
	char buf[MAX_MSG_LEN]; 
	int msgSize; 
	char clientInet [INET_ADDR_LEN]; 
	u_short port = ntohs (pClientAddr->sin_port); 
 
	inet_ntoa_b (pClientAddr->sin_addr, clientInet); 
	free (pClientAddr); 
  
 	FOREVER 
		{ 
		msgSize = read (sock, buf, MAX_MSG_LEN); 
 
		/* Read error ? */ 
		if (msgSize < 0) 
			{ 
			close (sock); 
			error ("Read failed"); 
			} 
 
		/* Connection closed ? */ 
		else if (msgSize == 0) 
			{ 
			close (sock); 
			break; 
			} 
 
		/* Get client message and service it*/ 
		else 
			{ 
			printf ("Task %s servicing client from" 
					" inet %s, port %d\n\n",taskName(0), 
					clientInet, port); 
			} 
		} 
	} 
 
 
void error 
	( 
	char * str 
	) 
	{ 
	perror (str); 
	exit (1); 
	}