nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

学习 C/C++ (Part 23: UDP and SRT) #294

Open nonocast opened 2 years ago

nonocast commented 2 years ago

shell

tcp

udp

lsof

 ~ lsof -Pi:3000
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
nc      71649 nonocast    3u  IPv4 0x5fc9824807db3e37      0t0  TCP *:3000 (LISTEN)
nc      71683 nonocast    3u  IPv4 0x5fc982433b42655f      0t0  UDP *:3000 
~ 
~ lsof -PiTCP:3000
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
nc      71649 nonocast    3u  IPv4 0x5fc9824807db3e37      0t0  TCP *:3000 (LISTEN)
~ lsof -PiUDP:3000
COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
nc      71683 nonocast    3u  IPv4 0x5fc982433b42655f      0t0  UDP *:3000

UDP

server.c

#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(void) {
  uint16_t port = 3000;
  struct sockaddr_in servaddr = {.sin_family = AF_INET, .sin_port = htons(port), .sin_addr.s_addr = htonl(INADDR_ANY)};
  int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
  printf("udp server running ...\n");

  // recv
  uint8_t buffer[1024];
  struct sockaddr_in client;
  socklen_t clientlen = sizeof(client);

  while (true) {
    memset(buffer, 0x00, 1024);
    int n = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr *) &client, &clientlen);
    struct hostent *clienthost =
        gethostbyaddr((const char *) &client.sin_addr.s_addr, sizeof(client.sin_addr.s_addr), AF_INET);
    char *clientaddr = inet_ntoa(client.sin_addr);
    printf("server received datagram from %s (%s)\n", clienthost->h_name, clientaddr);
    sendto(sockfd, buffer, n, 0, (struct sockaddr *) &client, clientlen);
  }

  return 0;
}

随便发几条消息,程序输出如下:

make run
udp server running ...
server received datagram from localhost (127.0.0.1)
server received datagram from huis-mac-mini.lan (192.168.2.190)
server received datagram from huis-mac-mini.lan (192.168.2.190)
server received datagram from localhost (127.0.0.1)

udp和tcp的模型差别还是比较大的,udp在ip上的封装更少更直接,tcp额外增加了逻辑去除抖动和丢包,所以应该根据业务选择合适的模型。

SRT

// TODO:

参考阅读