如何用c写一个服务器,可以改变服务器上video/audio的进度?

How to write a server by c that can change the progress of video/audio on the server?

如何用c写一个服务器,可以改变video/audio在服务器上的进度?

我用c写了一个服务器程序,但是当我使用javascript改变<video>元素的currentTime时,从这个c服务器获取源代码,视频总是开始于开始。

响应文件请求代码如下:

void send_file()
{
  // count file length
  int fd = open(file, O_RDONLY);
  int file_len = lseek(fd, 0, SEEK_END);

  // send http header
  if (strcmp(type, ".mp4") == 0) {
    sprintf(type, "video/mp4");
  } else {
    // ...
  }
  sprintf(head, 
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: %s\r\n"
      "Content-Length: %d\r\n"
      "\r\n"
      , type
      , file_len
      );
  send(c_sock, head, strlen(head), 0);

  // send file content
  lseek(fd, 0, SEEK_SET);
  memset(msg, 0, sizeof(msg));

  int delta = 0;
  while (delta < file_len) {// read by lines
    memset(msg, 0, 4096);
    int size = read(fd, msg, 1024);
    delta += size;
    // send(c_sock, msg, strlen(msg), 0);
    send_helper(msg, size);
  }

  close(fd);
}

void send_helper(char *content, int size)
{
  while (size > 0) {
    int delta = send(c_sock, content, size, 0);
    if (delta <= 0) return;
    size -= delta;
    content += delta;
  }
}

我正在使用

  while (1) {
    c_sock = accept(s_sock, NULL, NULL);
    if (c_sock != -1) {
      int nread = recv(c_sock, buf, sizeof(buf), 0);
    }
  }

接收来自浏览器的请求。

请求 mp4 文件时,请求和响应 header 将是

GET /source/1.mp4 HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36
Accept-Encoding: identity;q=1, *;q=0
Accept: */*
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: no-cors
Sec-Fetch-Dest: video
Referer: http://127.0.0.1:8000/
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7,fr;q=0.6
Range: bytes=0-
HTTP/1.1 200 OK
Content-Type: video/mp4
Content-Length: 105270886

使用 apache 服务器时,header 将是

Accept: */*
Accept-Encoding: identity;q=1, *;q=0
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7,fr;q=0.6
Connection: keep-alive
Host: 127.0.0.1
If-Modified-Since: Sat, 08 Aug 2020 11:04:55 GMT
If-None-Match: "6464e66-5ac5bb1097630"
Range: bytes=0-4653055
Referer: http://127.0.0.1/
Sec-Fetch-Dest: video
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36
HTTP/1.1 206 Partial Content
Date: Sun, 09 Aug 2020 05:09:46 GMT
Server: Apache/2.4.41 (Ubuntu)
Last-Modified: Sat, 08 Aug 2020 11:04:55 GMT
Accept-Ranges: bytes
ETag: "6464e66-5ac5bb1097630"
Content-Type: video/mp4
Content-Range: bytes 58392576-105270885/105270886
Content-Length: 46878310

这个问题(视频总是从begin开始)只是因为request和response head(例如Content-Range)?如何解决这个问题?

谢谢。

您的服务器必须声明它接受 Accept-Ranges: bytes 的范围,然后它必须处理来自客户端的 Range header,仅提供请求的部分并在Content-Range header - 与您在发送到 Apache 的请求中看到的完全一样。

有关准确但必要的详细信息,请遵循实际标准,即 RFC 7233 - Hypertext Transfer Protocol (HTTP/1.1): Range Requests