select socket call send and recv synchronization

后端 未结 1 1683
野趣味
野趣味 2021-01-28 11:27

I am using the select call and accepting the connection from \"X\" no of clients. I made duplex connection i.e. server to client and client to server. When connection is establi

相关标签:
1条回答
  • 2021-01-28 11:58

    Sketch of the kind of buffer code you need. (To allow partial reads/writes, the buffers need to be persistent between calls) BTW: you really need to handle the -1 return from read() and write() because they would seriously disturb your buffer-bookkeeping. EINTR + EAGAIN/EWOULDBLOCK is very common.

    struct buff {
            unsigned size;
            unsigned bot;
            unsigned top;
            char *buff;
            };
    struct buff bf = {0,0,0,NULL};
    
    initialisation:
    
    bf.buff = malloc(SOME_SIZE);
            /* ... error checking omitted */
    bp.size = SOME_SIZE;
    bp.bot = bp.top =0;
    
    reading:
    
    unsigned todo;
    int rc;
    
            /* (maybe) shift the buffer down to make place */
    todo =  bf.top - bf.bot;
    if (todo) {
            memmove (bf.buff, bf.buff + bf.bot, todo);
            bf.top = todo; bf.bot = 0;
            }
    
    todo = bf.size - bf.top;
    
    if (!todo) { /* maybe throttle? ... */ return; }
    rc = read (fd, bf.buff+bp.top, todo);
            /* ... error checking omitted */
    if (rc == -1) switch (errno) {...}
    else if (rc == 0) {...}
    else    {
            total_read += rc;
            bp.top +=  rc;
            }
    
    
    writing:
    
    unsigned todo; 
    int rc;
    
    todo =  bf.top - bf.bot;
    if (!todo) { /* maybe juggle fd_set ... */ return; }
    rc = write (fd, bf.buff+bp.bot, todo);
            /* ... error checking omitted */
    if (rc == -1) switch (errno) {...}
    else if (rc ==0) { ...}
    else    {
            bp.bot += rc;
            total_written += rc;
            if (bp.bot == bp.top) bp.bot = bp.top =0;
            }
    /* ... this is the place to juggle the fd_set for writing */
    
    0 讨论(0)
提交回复
热议问题