1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#define PORTS 1981
void serveur(int sock);
typedef struct struc_client {int num_sck;
char ip;
} s_client;
s_client *clients[100];//tableau contenant les clients
s_client *client;//un client
int sock, nsock,i;
int nb_client;
main()
{
int sock, nsock;
struct sockaddr_in adr_s, adr_c;
typedef struct sockaddr SOCKADDR;
client = (s_client *) malloc(sizeof(s_client));
socklen_t lg_adr_c = sizeof(adr_c);
sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sock != -1) {printf("La socket %d est maintenant ouverte en mode TCP/IP\n", sock);}
bzero(&adr_s,sizeof(adr_s));
adr_s.sin_family=AF_INET;
adr_s.sin_port= htons(PORTS);
adr_s.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock,(SOCKADDR *)&adr_s,sizeof(adr_s))!=-1){
printf("construction adresse ok \n");
}
if(listen(sock,5)!=-1){
printf("Patientez pendant qu'un client se connecte sur le port %d...\n", PORTS);
}
pthread_t thread_serveur;
while(1)
{
nsock = accept(sock,(SOCKADDR *)&adr_c,&lg_adr_c);
if(nsock!=-1){
printf("un nouveau client vient de se connecter : %s \n",inet_ntoa(adr_c.sin_addr));
client->num_sck = nsock;
client->ip = inet_ntoa(adr_c.sin_addr);
clients[nb_client] = client;
printf("socket = %d\n",client->num_sck);
pthread_create(&thread_serveur, NULL, (void*)&serveur,client->num_sck);
nb_client++;
printf("il y a maintenant %i client sur le serveur.\n",nb_client);
for(i=0;i<=nb_client-1;i++){
printf("et il existe la sockets : %d\n",clients[i]->num_sck);
}
}
}
}
void serveur(int sock){
char buf[500];
printf("entrer dans thread \n");
while(1){
if (read(sock,buf,500)!=-1){
printf("read\n");
};
for(i=0;i<=nb_client-1;i++){
write(clients[i]->num_sck,&buf,500);
printf("message envoyer sur le socket : %d\n",clients[i]->num_sck);
}
}
} |
Partager