Página 1 de 1

TCP-IP - Codigo fonte bloco Cliente de chat em C.

Enviado: 21 Out 2006 01:54
por rochinha

Código: Selecionar todos

/*********************************************************************
/	PROGRAM: icu2 (main.c) Client Program
/	AUTHOR:  Nathan Buggia
/	DATE:    May 2, 1998
/*********************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <errno.h>

#include <stdlib.h>
//- - - - - - - - - - - - - - - - - - - - #define's

#define ICU2_PORT 3033
#define IO_BUFFER 255 

//- - - - - - - - - - - - - - - - - - - - prototypes

void doIntro(void);
void openChat(void); 
void doParentTasks(void);
void doChildTasks(void);
pid_t Fork(void);

//- - - - - - - - - - - - - - - - - - - - global vars 

char CONNECTION_REQUEST[5] = "+EST";		// client requests connection
char ACCEPT_CONNECTION[5] = "+CON";		// server accepts conneciton
char NOT_ACCEPTED[5] = "-NOA";			// server is full and did not accept connection
char DISCONNECTING[5] = "-DIS";			// the client is going to disconnect

char send_data[100];
char prompt[32];
char username[32];

int sockfd;
struct sockaddr_in address;
char input[IO_BUFFER], output[IO_BUFFER];

char *argv_1;					       // export the argv so that we can use it else where.

char temp[20];
//- - - - - - - - - - - - - - - - - - - - int main(int,char**) 
int main(int argc, char **argv){

	pid_t cpid;

	if(argc != 2){						// check for correct command line args.
		printf("usage: icu2 IPaddress\n");
		return -1;
	}

	argv_1 = argv[1];					// export argv for use in doParentTasks.

	doIntro();							// get username
	
	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){	// create the socket object.
		printf("Error, could not allocate socket.\n");
		return(-1);
	}

	memset(&address, 0, sizeof(address));			// set the socket object to 0.

	address.sin_family = AF_INET;				    // say the socket is an Inet socket.
	address.sin_port = htons(ICU2_PORT);			// specify the socket port.

	if(inet_pton(AF_INET, argv[1], &address.sin_addr) <= 0){	// is it a vaild IP address?
		printf("Error, domain %s invalid.", argv[1]);
		return(-1);
	}	
	
    // can we connect?		
	if(connect(sockfd, (struct sockaddr *)&address, sizeof(address)) < 0){	
		printf("Error, could not establish connection. (errno %d).\n",errno);
		return (-1);
	}

	openChat();						// can we login to the server?

	/*******************************************
	 * now we are going to fork so that we may
	 * wait on two inputs, one form the server
	 * and one from the user at stdin.
	 ******************************************/
	
	if( (cpid = Fork()) == 0){			 // now we are a child process
		doChildTasks();
		return 0;					     // so we never get to the parent loop.
	}

	doParentTasks();					     // now the parent goes to work.	

	sprintf(temp, "%s %d", "kill -9 ", cpid);
	printf("Killing child process with a system call: %s\n", temp);
	system(temp);

	close(sockfd);						// now we are all done.
	return 0;						    // as letterman says, the shows over kids...
}

//- - - - - - - - - - - - - - - - - - - - void doIntro(void)
void doIntro(void){
	
	printf("\n****************************************\n");
        printf("* Icu2: The Ultimate Chat Client.\n");
        printf("*\n");
        printf("* Please enter your name: ");

        scanf("%s", username);

        printf("*\n");
        printf("* Welcome %s, thank you for choosing Icu2!\n", username);

	strcat(prompt, "Say this! -=[ ");

	printf("*\n");
	printf("* Your prompt has been set to: %s\n", prompt);
	printf("* \n");
	printf("*****************************************\n");
}

//- - - - - - - - - - - - - - - - - - - - void openChat(void) 
void openChat(void){

	write(sockfd, &CONNECTION_REQUEST, IO_BUFFER);		// send an R, request a connection.
        read(sockfd, &input, IO_BUFFER);
       	
	if( strncmp(input, ACCEPT_CONNECTION, 4) ){
		printf("Icu2 server is too busy, try back later. %s\n", input);
		close(sockfd);
		exit(0);
	}else{
		printf("Connected to Icu2 server!\n");
	}
}

//- - - - - - - - - - - - - - - - - - - - void doParentTasks(void)
void doParentTasks(void){

	char temp[IO_BUFFER];
	int tsockfd;									// temperary socket stuff.
    struct sockaddr_in taddress;					// more temp socket stuff.
	char quit[6] = "/quit";
	
	printf("%s", prompt);
	getchar();

	for(;;){
		fgets(temp, IO_BUFFER, stdin);

		printf("%s", prompt);

		strcpy(output, username);
		strcat(output, " - ");
		strcat(output, temp);

//		printf("you said - %s\n", output);

		/**********************************************
		 * I am sure they have something to send so
		 * we will open up a socket to send it to them.
		 **********************************************/
	
	        if((tsockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        	        printf("Error, could not allocate socket.\n");
	            exit(-1);
       		 }

  	      	memset(&taddress, 0, sizeof(taddress));

	        taddress.sin_family = AF_INET;
	        taddress.sin_port = htons(ICU2_PORT);

	        if(inet_pton(AF_INET, argv_1, &taddress.sin_addr) <= 0){
	                printf("Error, domain %s invalid.", argv_1);
	                exit(-1);
	        }
	
	        if(connect(tsockfd, (struct sockaddr *)&taddress, sizeof(taddress)) < 0){
	                printf("Error, could not establish connection. (errno %d).\n",errno);
	                exit (-1);
	        }

		/*********************************************
		 * done creating a socket.
		 ********************************************/

		if( !strncmp(temp, quit, 5) ) {
		  printf("Preparing to exit icu2...\n");
		  sprintf(temp, "%s %d", DISCONNECTING, sockfd);
		  printf("Sending \"%s\" to the server...\n", temp);
		  write(tsockfd, &temp, IO_BUFFER);
		  break;
		}/* endif */

		write(tsockfd, &output, IO_BUFFER);

	}
}

//- - - - - - - - - - - - - - - - - - - - void doChildTasks(void)
void doChildTasks(void){

	for(;;){
		read(sockfd, &input, IO_BUFFER);
//		write(stdout, &input, IO_BUFFER);
		printf("%s\n", input);
	}
}

//- - - - - - - - - - - - - - - - - - - pid_t Fork(void)
pid_t Fork(void){

	pid_t pid;
	
	if( (pid = fork()) == -1){
		printf("Error forking, your are dead!\n");
		exit(-1);
	}
	
	return pid;
}
Parte Servidor em https://pctoledo.org/forum/viewto ... 8551#18551