带外数据

头文件为sock.h,封装文件为wrap.c

服务器:

#include "sock.h"
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <strings.h>
#include <signal.h>

#define MAXSIZE 80

static int connfd;

void usage(const char *info)
{
 printf("Usage: %s <PORT>\n", info);
 exit(0);
}

void catch_sig(int sig)
{
 if(sig == SIGURG){

  char buf[MAXSIZE] = {0};

  recv(connfd, buf, MAXSIZE, MSG_OOB);
  printf("urgent data: %s\n", buf);
 }
}

int main(int argc, char **argv)
{
 if(argc != 2)
  usage(argv[0]);

 int sockfd;
 sockfd = Socket(AF_INET, SOCK_STREAM, 0);

 int on = 1;
 Setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);

 struct sockaddr_in srvaddr, cliaddr;
 bzero(&srvaddr, sizeof srvaddr);
 srvaddr.sin_family = AF_INET;
 //Inet_pton(AF_INET, argv[1],
 // (struct sockaddr *)&srvaddr.sin_addr);
 srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
 srvaddr.sin_port = htons(atoi(argv[1]));

 Bind(sockfd, (struct sockaddr *)&srvaddr,
  sizeof srvaddr);

 Listen(sockfd, 5);

 socklen_t len;
 char recv[MAXSIZE];

 len = sizeof cliaddr;
 bzero(&cliaddr, len);
 connfd = Accept(sockfd, (struct sockaddr *)&cliaddr, &len);

 /********************************/
 signal(SIGURG, catch_sig);
 fcntl(connfd, F_SETOWN, getpid());
 /********************************/

 printf("new connection: %s:%hu\n",
  inet_ntoa(cliaddr.sin_addr),
  ntohs(cliaddr.sin_port));

 int n;
 while(1){
  bzero(recv, MAXSIZE);
  if((n=read(connfd, recv, MAXSIZE)) <= 0)
   break;

  write(STDOUT_FILENO, recv, strlen(recv));
 }
 return 0;
}

客服端:

#include "sock.h"
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#define MAXLINE 80

void usage(const char *info)
{
 printf("Usage: %s <srv's IP> <srv's PORT>\n", info);
 exit(0);
}

int main(int argc, char **argv)
{
 if(argc != 3)
  usage(argv[0]);

 int sockfd;
 sockfd = Socket(AF_INET, SOCK_STREAM, 0);

 struct sockaddr_in srvaddr;
 bzero(&srvaddr, sizeof srvaddr);
 srvaddr.sin_family = AF_INET;
 Inet_pton(AF_INET, argv[1],
  (struct sockaddr *)&srvaddr.sin_addr);
 srvaddr.sin_port = htons(atoi(argv[2]));

 Connect(sockfd, (struct sockaddr *)&srvaddr,
    sizeof srvaddr);

 char buf[MAXLINE];
 while(1){
  write(sockfd, "123", 3);
  sleep(1);

  send(sockfd, "4", 1, MSG_OOB);
  sleep(1);

  write(sockfd, "56", 2);
  sleep(1);

  send(sockfd, "78", 2, MSG_OOB);
  sleep(1); }
 return 0;
}

你可能感兴趣的:(数据)