Lo sistemato e lo testato funziona alla perfezione diciamo che sembra una chat anzi è una chat ...
ecco il codice che ho sistemato :
Server:
codice:
//
// main.c
// server
//
// Created by GHIRO9 on 30/08/12.
// Copyright (c) 2012 GHIRO9. All rights reserved.
//
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<pthread.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 256
void *gestisci(void *socket) {
printf("gestisci(): creato il thread\n");
char buf[N];
while (1) {
ssize_t byte=0;
if((byte=recv((int)socket, buf, sizeof(buf), 0))!=-1)
{
printf("Dati ricevuti: %s\n",buf);fflush(stdout);
if (strcmp(buf, "quit\n")==0) {
memset(buf, 0, sizeof(buf));
break;
}
memset(buf, 0, sizeof(buf));
}
else{
perror("errore ricezzione\n");fflush(stdout);
}
}
printf("sono fuori\n");fflush(stdout);
close((int)socket);
pthread_exit (0);
}
int main(int argc, char *argv[]){
int s_fd, c_fd, portno;
socklen_t len;
pthread_t tid;
char buffer[N];
struct sockaddr_in sin, client;
s_fd=socket(AF_INET,SOCK_STREAM,0);
portno = atoi(argv[1]);
sin.sin_family = AF_INET;
sin.sin_port = htons(portno);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
len = sizeof(client);
bind(s_fd, (struct sockaddr *) &sin, sizeof(sin));
listen(s_fd,5);
while (1){
c_fd = accept(s_fd,(struct sockaddr *)&client, &len);
inet_ntop(AF_INET,&client.sin_addr,buffer,sizeof(buffer));
printf("Request from client %s\n",buffer);
pthread_create(&tid,NULL,gestisci,(void *)c_fd);
pthread_detach(tid);//serve per liberare risorse
}
close(s_fd);
return 0;
}//end server
questo è il client:
codice:
//
// main.c
// client
//
// Created by GHIRO9 on 30/08/12.
// Copyright (c) 2012 GHIRO9. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define N 256
int main(int argc, char *argv[]) {
int c_fd,portno,lung,abba;
struct sockaddr_in sin;
struct hostent *hp;
char buffer[N];
if (argc != 3) {
printf("Illegal number of arguments");
exit(1);
}
if ((hp = gethostbyname(argv[1])) == 0) {
perror("tom: gethostbyname");
exit(1);
}
c_fd = socket(AF_INET, SOCK_STREAM, 0);
portno=atoi(argv[2]);
sin.sin_family = AF_INET;
memcpy((char *)&sin.sin_addr, (char *)hp->h_addr, hp->h_length);
sin.sin_port = htons(portno);
if(connect(c_fd, (struct sockaddr *) &sin, sizeof(sin)) < 0){
perror("connect");
return 1;
}
while (1) {
printf("(CLIENT) Scrivere un messaggio: ");
fgets(buffer,N,stdin);
if((send(c_fd, buffer, strlen(buffer), 0))!=-1)
{
printf("Messaggio inviato");
}
else{
perror("send");
}
}
return 0;
}//end client