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

Aqui você poderá oferecer suas Contribuições, Dicas e Tutoriais (Texto ou Vídeo) que sejam de interesse de todos.

Moderador: Moderadores

Avatar do usuário
rochinha
Administrador
Administrador
Mensagens: 4664
Registrado em: 18 Ago 2003 20:43
Localização: São Paulo - Brasil
Contato:

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

Mensagem por rochinha »

Código: Selecionar todos

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

//- - - - - - - - - - - - - - - - - - - - #define's

#define ICU2_PORT 3033
#define LISTEN_QUEUE_SIZE 5
#define MAX_CONNECTIONS 50
#define IO_BUFFER 255

#define CLIENTFD_INIT -1

//- - - - - - - - - - - - - - - - - - - - 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";			// client requeting to disconnect

int clientfd[MAX_CONNECTIONS];			// array of connected clients' sockfd's
int current_connections = 0;				// number of clients currently connected

int listenfd;								// fd of the listening socket.
int sockfd;									// fd of the syncronus socket.
struct sockaddr_in address;				// sockfd's struct object.

char input[IO_BUFFER], output[IO_BUFFER];	// input and output buffers.
 
char *temp;
char tempbuf[6];
int i;

//- - - - - - - - - - - - - - - - - - - - int main() 

int main(){

	listenfd = socket(AF_INET, SOCK_STREAM, 0);

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

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

    bind(listenfd, (struct sockaddr *)&address, sizeof(address));
    listen(listenfd, LISTEN_QUEUE_SIZE); 
	
	for(i = 0; i <= MAX_CONNECTIONS-1; i++) {
	  clientfd[i] = CLIENTFD_INIT;
	}/* endfor */

	for(;;){
		sockfd = accept(listenfd, (struct sockaddr *) NULL, NULL);

		read(sockfd, &input, IO_BUFFER);

		printf("\n\nServer receives: %s\n",input);

		if( !strncmp(input, CONNECTION_REQUEST, 4) ){	// if it is a connection request.
			printf("Server has a connection request.\n");
			if( current_connections < MAX_CONNECTIONS ){
				printf("There is room for another connection.\n");
				clientfd[current_connections] = sockfd;
				current_connections++;
				write(sockfd, &ACCEPT_CONNECTION, IO_BUFFER);
			}else{
				printf("Server is full!\n");
				write(sockfd, &NOT_ACCEPTED, IO_BUFFER);
			}
		}

		/* Disconnect request from client */
		else if( !strncmp(input, DISCONNECTING, 4) ) {
		  printf("Server received a disconnect request with sockfd == ");
		  sockfd = -1;
		  sscanf( input, "%5c%d", tempbuf, &sockfd);
		  printf( "%d\n", sockfd);

		  if(sockfd == -1) {
		    printf("Error while reading -DIS...\n");
		    printf("This data will be ignored.\n");
		  }/* endif */

	      else {
		    printf("Successful -DIS_# reading\n");
		    while( clientfd[i] != sockfd && i <= MAX_CONNECTIONS-1 ) {
		      i++;
		    }
		    clientfd[i] = CLIENTFD_INIT;
//	  	    close(sockfd);
		  }/* endelse */

		}/* endif */

		/* Anything else will be sent to all connected users */
		else{

		  printf("Printing this out to all clients: \n");
		  printf("\t%s\n", input);

		  /* writing input to all active sockets */
		  for(i = 0; i <= MAX_CONNECTIONS-1; i++) {
		    sockfd = clientfd[i];
		    if( sockfd != CLIENTFD_INIT) {
		      write(sockfd, &input, IO_BUFFER);
		    }/* endif */

		  }/* endfor */


		}/* endelse */
	}

	return 0;
}
Parte cliente em https://pctoledo.org/forum/viewtopic.php?t=4610
OPS! LINK QUEBRADO? Veja ESTE TOPICO antes e caso não encontre ENVIE seu email com link do tópico para [url=mailto://fivolution@hotmail.com]fivolution@hotmail.com[/url]. Agradecido.

@braços : ? )

A justiça divina tarda mas não falha, enquanto que a justiça dos homens falha porque tarda.
Responder