Send indeterminate amount of JSON strings via socket

Asked

Viewed 60 times

2

have an application cliente/servidor where the client makes a request to the server and the server makes a query to a banco de dados and then returns this data to the client in the format JSON, as I do not know how many records I have in my table thought to send each record in one send(), however in customer I am losing the data of the first send(), and the buffer of the first recv() is storing the data of send() sequent

Código do servidor:

while((row = mysql_fetch_row(res))){
    sprintf(jobj_string, "{ \"nomeUsuario\" : \"%s\", \"idUsuario\" : \"%s\" }", row[1], row[0]);
    if((send(socketNovo, jobj_string, strlen(jobj_string), 0)) == SOCKET_ERROR){
        perror("Falha ao enviar usuario");
        exit(0);
    }
}

Código do cliente:

for(;;){
    if((recv(socketServidor, jobj_string, 300, 0)) == SOCKET_ERROR){
        perror("socket recv");
        exit(0);
    }
    jobj = json_tokener_parse(jobj_string);
    if(jobj != NULL)
        json_object_object_foreach(jobj, key, val){
            /* processa o JSON */
        }
}

what the server sends:

{ "nomeUsuario" : "user1", "idUsuario" : "1" }
{ "nomeUsuario" : "user2", "idUsuario" : "2" }
{ "nomeUsuario" : "user3", "idUsuario" : "3" }
{ "nomeUsuario" : "user4", "idUsuario" : "4" }

each row being a send();

what the client’s first recv buffer stores:

: "user2", "idUsuario" : "2" }
{ "nomeUsuario" : "user3", "idUsuario" : "3" }
{ "nomeUsuario" : "user4", "idUsuario" : "4" }

or lost data from the first send(), and killed the second, I used the wireshark and verified that the server is sending the data correctly, another idea would be to send all the records in only one send(), but as I do not have how to determine quantity records exist in my bank, I run the risk of bursting the size of the buffer customer’s.

How would be the best way to send the records to the customer without knowing the size?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.