user800799
user800799

Reputation: 3023

Read problem with epoll

I have this while loop and this code is working. The problem is that if I have reduced the buffer size and send bigger data than the buffer size it receive the data separately. For example, if I send 170 bytes(100 byte buffer) then it reads first 100 bytes and again it reads 70bytes. What is the best way to handle this? If multiple users send data like this then how do I concatenate those separated packets? Thanks in advance..

while(m_severRun){
    int event_cnt = epoll_wait(m_epfd, m_events, EPOLL_SIZE, -1);
    if(event_cnt == -1){
        perror("epoll_wait error \n");
        break;
    }

    for(int i=0; i<event_cnt; i++){
        if(m_events[i].data.fd == m_serverSock){

            printf("ServerManager::eventAcceptLoop, A Client has been connected \n");

            struct sockaddr_in clnt_adr;
            socklen_t adr_sz = sizeof(clnt_adr);


            int clnt_sock = accept(m_serverSock, (struct sockaddr*)&clnt_adr, &adr_sz);
            if(!addClient(clnt_sock))
                break;
        }
        else{

            int str_len = read(m_events[i].data.fd, buf, BUF_SIZE);
            printf("read %d \n", str_len);

            if(str_len == 0){
                if(!removeClient(m_events[i].data.fd))
                    break;
                close(m_events[i].data.fd);

            }
            else {
                printf("ServerManager::eventAcceptLoop, A message has been received \n");
                //pushWork(buf);
                //write(m_events[i].data.fd, buf, str_len);
            }
        }
    }//for loop end
}//while loop end

Upvotes: 1

Views: 423

Answers (1)

Martin James
Martin James

Reputation: 24907

Well, though it's unlikely, it is possible that your 170-byte client send could arrive at your server and be presented as 170 read() returns with a str_len of 1. That's just how TCP is - it streams bytes. If you have to concatenate bytes into some sort of protocol-unit, then you will have to explicitly do this in your code. The best way for your app depends on the protocol and how you handle the protocol-units. That's very app-dependent. If, for example, you protocol is CRLF-delimited text, you could copy each received byte into some buffer class until the delimiter is found, then pushwork(currentBufferInstance).

It all depends on your protocol and how you wish/need to communicate your data around your server.

Rgds, Martin

Upvotes: 1

Related Questions