Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7998815
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T15:19:29+00:00 2026-06-04T15:19:29+00:00

I’m writing a multithreaded C++ server and a Java client using TCP. It works

  • 0

I’m writing a multithreaded C++ server and a Java client using TCP. It works fine for short strings, but when I want to send big strings (e.g. 40 characters), the server only receives a few of them, and the client is waiting for the response.

The multithreading part works fine.

Here you have the code. (Sorry for the comments and names of variables. I’m Spanish.)

Server C++

void* SocketHandler(void*);


int main(int argv, char** argc){



//Puerto en el que recibe
int host_port= 1101;

//Estructura usada para especificar una direccion local o remota a la que conectar un socket
struct sockaddr_in my_addr;

int hsock;
int * p_int ;
int errno;

socklen_t addr_size = 0;
int* csock;
sockaddr_in sadr;
pthread_t thread_id=0;

//Se inicializa socket
hsock = socket(AF_INET, SOCK_STREAM, 0);
//Para comprobar que el socket se ha inicializado correctamente
if(hsock == -1){
    printf("Error inicializando socket %d\n", errno);
    goto FINISH;
}

//Se reserva memoria
p_int = (int*)malloc(sizeof(int));
*p_int = 1;

//Se comprueba que al introducir las opciones del socket se introduzcan correctamente   
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
    (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
    printf("Error introduciendo opciones del socket %d\n", errno);
    //Se libera la memoria reservada
    free(p_int);
    goto FINISH;
}
//Se libera la memoria reservada
free(p_int);

//Se añade la familia de direcciones a la que pertenece IPV4
my_addr.sin_family = AF_INET ;
//Se añade el puerto que es
my_addr.sin_port = htons(host_port);

//Relleno de sin zero con 8 ceros
bzero((char *) &(my_addr.sin_zero), sizeof(my_addr.sin_zero));
//memset(&(my_addr.sin_zero), 0, 8);

//Se añade la dirección IP
my_addr.sin_addr.s_addr = INADDR_ANY ;

//Enlaza el socket con la dirección IP, puerto
if( bind( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){
    fprintf(stderr,"Error enlazando el socket, asegurate de que no hay nada más escuchando en este puerto %d\n",errno);
    goto FINISH;
}
//Se pone a escuchar
if(listen( hsock, 5) == -1 ){
    fprintf(stderr, "Error listening %d\n",errno);
    goto FINISH;
}


//Ahora se pasa a hacer las cosas en el servidor


addr_size = sizeof(sockaddr_in);

while(true){
    printf("Esperando a una conexión\n");
    //Se reserva memoria 
    csock = (int*)malloc(sizeof(long double));
    //Hay que encontrar porque no manda mas de x caracteres


    //LLamada que se bloquea esperando una conexion de un cliente
    if((*csock = accept( hsock, (struct sockaddr*)&sadr, &addr_size))!= -1){
        printf("---------------------\nRecibida conexión de %s\n",inet_ntoa(sadr.sin_addr));
        //Se crea un nuevo hilo por cliente, se llama a socket handler
        pthread_create(&thread_id,0,&SocketHandler, (void*)csock );
        //El almacenamiento del hilo puede ser reclamado cuando el hilo haya terminado
        pthread_detach(thread_id);
    }
    else{
        fprintf(stderr, "Error aceptando cliente %d\n", errno);
    }
}

FINISH:
;
}

void* SocketHandler(void* lp){
int *csock = (int*)lp;

//Buffer en donde se guarda lo recibido
char buffer[8192];
//Longitud del buffer
//int buffer_len = 8192;
//Contador para saber el número de caracteres del buffer
int bytecount;

//Relleno del buffer con ceros
bzero((char *) &buffer, sizeof(buffer));
//memset(buffer, 0, sizeof(buffer));
//Se recibe la informacion del socket y se comprueba que sea valida

//recv(buffer,offset,size,socketflags) 
//buffer es un array de bytes que es la localización en donde se van a guardar los datos
//offset es la posicion en el buffer de datos desde la cual se quiere empezar a guardar
//size es el número de bytes a recibir
//socketflags es la combinacion de flas que se quieren utilizar 0 significa ninguno 
/*if((bytecount = recv(*csock, buffer, sizeof(buffer), 0))== -1){
    fprintf(stderr, "Error recibiendo los datos %d\n", errno);
    goto FINISH;
}*/


if((bytecount = read(*csock,buffer,sizeof(buffer)))== -1){
        fprintf(stderr, "Error recibiendo los datos %d\n", errno);
    goto FINISH;
}

printf("Bytes recibidos %d\nstring recibido %s\n", bytecount, buffer);
//Copia el string al buffer
//strcat(buffer, " SERVER ECHO");




//Se tienen que poner parentesis por el uso de go to de arriba
{       


    string comando = buffer;


    if(comando.compare("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz") == 0){

        strcpy(buffer,"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");


    }

}


//Envía el mensaje de vuelta con el string añadido

//send(buffer,offset,size,socketflags) 
//buffer es un array de bytes que contiene los datos a ser enviados
//offset es la posicion en el buffer de datos desde la cual se quiere empezar a enviar datos
//size es el número de bytes a enviar
//socketflags es la combinacion de flas que se quieren utilizar 0 significa ninguno

{
    //Se hace esto ya que en el cliente parece que si no le llegua salto de linea no continua, y se queda esperando
string bufferbarran =  buffer;
bufferbarran +="\n";    
strcpy(buffer,bufferbarran.c_str());
/*
if((bytecount = send(*csock, buffer, strlen(buffer), 0))== -1){
    fprintf(stderr, "Error enviando los datos %d\n", errno);
    goto FINISH;
}
*/
if((bytecount = write(*csock,buffer,strlen(buffer)))== -1){
        fprintf(stderr, "Error enviando los datos %d\n", errno);
    goto FINISH;
}
}

printf("Bytes enviados %d\n", bytecount);


FINISH:
//Se libera la memoria reservada

free(csock);

return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T15:19:30+00:00Added an answer on June 4, 2026 at 3:19 pm

    Instead of calling read() directly in the socket server (and client), you should use select() to know when the socket is ready to be read or written. Its considered bad practice to just call read/write without calling select(). select() will block until the socket is ready to be read/written or until it times out, if you configure a timeout.

    Here is a good example where they use select(): c++ Socket select and receive problem

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
I have a French site that I want to parse, but am running into
I want to construct a data frame in an Rcpp function, but when I
I have thousands of HTML files to process using Groovy/Java and I need to
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
Seemingly simple, but I cannot find anything relevant on the web. What is the
I want use html5's new tag to play a wav file (currently only supported

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.