|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Junior Member
Iscritto dal: May 2012
Messaggi: 5
|
[C] read da socket, problemi!
Ciao a tutti, sto riscontrando dei problemi con una lettura da socket. Sto realizzando un server multithread che gestisce più clienti (contemporaneamente). Tuttavia alcuni messaggi letti dal socket non vengono ricevuti correttamente dal server. Ad esempio questo è un output che ottengo spesso:
"Server ricerve: X, 15, provaprovaprova Server riceve: X, 15, provaprovaprova Server riceve: , 0, " Il messaggio inviato dai clienti al momento è sempre lo stesso, e il server non deve far altro che leggerlo e stamparlo. Sul socket scrivo un buffer così realizzato: da una struttura del tipo: Codice:
messaggio{ char type; unsigned int l; char buffer[256]; }messaggio_t impacchetto il messaggio in un buffer e lo invio: Codice:
messaggio_t *msg; //struttura riempita ed allocata altrove buffer[sizeof(messaggio_t)+1]; memset(buffer, '\0', sizeof(messaggio_t)+1); buffer[0] = msg->type; (*(unsigned int*)&buffer[1]) = msg->l; memcpy(&buffer[sizeof(unsigned int)+1], msg->buffer, msg->l); buffer[msg->l+sizeof(unsigned int)+1] = '\n'; inviati = write(sock, buffer, msg->l+sizeof(unsigned int)+2); Codice:
void main(){ //inizializzazione //accetto connessioni while(1){ if( accept(socket, NULL, 0) ){ pthread_create() //thread detached, non riporto per semplicità. } } } void *thread_routine(){ char buffer[sizeof(message_t)+1] = {0}; messaggio_t *richiesta = calloc(); letti = read(sock, buffer, sizeof(messaggio_t)); richiesta->type = buffer[0]; richiesta->length = *((unsigned int*)&buffer[1]); strcpy(msg->richiesta, &buffer[sizeof(unsigned int)+1]); printf("Server riceve: %d, %c, %s\n", richiesta->l, richiesta->type, richiesta->buffer); } Ultima modifica di Smoke666 : 28-12-2012 alle 10:43. Motivo: .. |
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 09:52.