服务器客户端(TCP实现)(2)

while (nleft > 0) {
  if ((nwriten = write (fd, bufp, nleft)) <= 0) {
   if (EINTR == errno)
    nwriten = 0;
   else
    return -1;
  }

nleft -= nwriten;
  bufp += nwriten;
 }

return n;
}

/*read line from fd*/
ssize_t readline (int fd, void *buf, size_t maxlen)
{
 ssize_t n, rc;
 char c, *bufp;

bufp = buf;
 for (n = 1; n < maxlen; n ++) {
again:
  if (1 == (rc = read (fd, &c, 1))) {
   *bufp ++ = c;
   if ('\n' == c)
    break;  /*newline is stored*/
  } else if (rc == 0) {
   *bufp = 0;
   return (n - 1);  /*EOF, n-1 bytes were read*/
  } else {
   if (EINTR == errno) /*interrupt*/
    goto again;
   return -1;  /*Erro, set the errno by read ()*/
  }
 }
 *bufp = 0;
 return n;
}

运行结果:

Linux网络编程--服务器客户端(TCP实现)

因为客户端没有指定IP地址和端口,所以其IP和端口都是内核随机分配的。

linux

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/865b1c4b62e2e70c376ece89e085574c.html