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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值