Unix Network Programming Episode 66

Performance

When an application calls sendto on an unconnected UDP socket, Berkeley-derived kernels temporarily connect the socket, send the datagram, and then unconnect the socket (pp. 762–763 of TCPv2). Calling sendto for two datagrams on an unconnected UDP socket then involves the following six steps by the kernel:

  • Connect the socket
  • Output the first datagram
  • Unconnect the socket
  • Connect the socket
  • Output the second datagram
  • Unconnect the socket

When the application knows it will be sending multiple datagrams to the same peer, it is more efficient to connect the socket explicitly. Calling connect and then calling write two times involves the following steps by the kernel:

  • Connect the socket
  • Output first datagram
  • Output second datagram

In this case, the kernel copies only the socket address structure containing the destination IP address and port one time, versus two times when sendto is called twice. [Partridge and Pink 1993] note that the temporary connecting of an unconnected UDP socket accounts for nearly one-third of the cost of each UDP transmission.

‘dg_cli’ Function (Revisited)

#include "unp.h"

void dg_client(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen)
{
    int n;
    char sendline[MAXLINE], recvline[MAXLINE+1];
    
    Connect(sockfd, (SA *)pservaddr, servlen);   

    while(Fgets(sendline, MAXLINE, fp)!=NULL)
    {
        Write(sockfd, sendline, strlen(sendline));

        n=Read(sockfd, recvline, MAXLINE);

        recvlien[n]=0;
        Fputs(recvline, stdout);
    }
}

dg_cli function that calls connect

Lack of Flow Control with UDP

#include "unp.h"

#define NDG 2000
#define DGLEN 1400

void dg_client(FILE *fp, int sockfd, const SA *pservaddr, socket_len servlen)
{
    int i;
    char sendline[DGLEN];
    
    for(i=0;i<NDG;i++)
    {
        Sendto(sockfd, sendline, DGLEN,0, pservaddr, servlen);
    }
}

dg_cli function that writes a fixed number of datagrams to the server

#include "unp.h"

static void recvfrom_int(int);
static int count;

void dg_echo(int sockfd, SA *pclientaddr, socklen_t clientlen)
{
    socklen_t len;
    char mesg[MAXLINE];

    Signal(SIGINT, recvfrom_int);

    for(;;)
    {
        len=clientlen;
        Recvfrom(sockfd, mesg, MAXLINE, 0, pclientaddr, clientlen);

        count++;
    }
}

static void recvfrom_int(int signo)
{
    printf("\nreceived %d datagrams\n", count);
    return;
}

dg_echo function that counts received datagrams

Guess you like

Origin blog.csdn.net/myfather103/article/details/82254495