Clipper On Line • Ver Tópico - TCP-IP - Codigo fonte bloco Servidor de chat em C.

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

 

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

Mensagempor rochinha » 21 Out 2006 01:57

/*********************************************************************
/   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 http://www.pctoledo.com.br/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 fivolution@hotmail.com. Agradecido.

@braços : ? )

A justiça divina tarda mas não falha, enquanto que a justiça dos homens falha porque tarda.
Avatar de usuário

rochinha
Membro Master

Membro Master
 
Mensagens: 4545
Data de registro: 18 Ago 2003 20:43
Cidade/Estado: São Paulo - Brasil
Curtiu: 806 vezes
Mens.Curtidas: 245 vezes



Retornar para Contribuições, Dicas e Tutoriais

Quem está online

Usuários vendo este fórum: Nenhum usuário registrado online e 6 visitantes


Ola Amigo, espero que meu site e forum tem lhe beneficiado, com exemplos e dicas de programacao.
Entao divulgue o link da Doacao abaixo para seus amigos e redes sociais ou faça uma doacao para o site forum...
MUITO OBRIGADO PELA SUA DOACAO!
Faça uma doação para o forum
cron
v
Olá visitante, seja bem-vindo ao Fórum Clipper On Line!
Efetue o seu login ou faça o seu Registro