webrtc之本地部署实践

578 阅读2分钟

前前后后折腾了近一个月的时间,终于是用原生webrtc实现了一对一音视频/直播/会议的所有我能想到的功能了。特别是这个会议模式,太废脑子了, 各种操作之后要进行同步状态,又没有使用mysql来保存数据,只是在express中用一个变量来保存了,费拉吧唧的各种对比,重复代码好多。不过好在都完成了,下个版本全部优化一遍,再接入MySQL以及 AI对话,冲!

这小节就来看看写完之后如何部署到本地看看效果,用一用试试水

第一步肯定是先在前端运行npm run build命令,打包出一个dist目录文件。

第二步在后端server.js文件中新增以下代码:

app.use(express.static('./dist'));
app.use(function (req,res,next) {
  const filePath = path.join(__dirname,'/dist/index.html'); // 使用 path.join 将文件路径转换为绝对路径
  res.sendFile(filePath);
});

这里要注意dist目录的位置,别直接照抄。这里用的是express框架,koa的话别抄。

第三步就是修改nginx的配置文件了。具体如下:

server {
    listen 8088; # 监听的端口号
    listen 443 ssl http2; # 必须使用http2
    server_name  192.168.18.36; # 你本地电脑的ip地址  在windows下cmd运行 ipconfig
    ssl_certificate      "D:\webRTC\192.168.18.36.pem"; # 证书在上一节已经讲过如何安装使用
    ssl_certificate_key  "D:\webRTC\192.168.18.36-key.pem"; #  证书在上一节已经讲过如何安装使用

    # http重定向到https
    if ($scheme = http) {
        return 301 https://$host:443$request_uri;
    }
    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        proxy_pass http://127.0.0.1:9000; # 这里就是信令服务启动的服务地址 ,就是你server.js中起服务的端口号
        # proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_set_header X-Forwarded-Proto $scheme;
        ## 信令核心配置 必须开启支持 websocket 
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        # proxy_redirect http:// https://;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

这个config配置可以直接照搬过去,注意修改下监听的端口号ip地址证书信令服务地址就好,其他不用动。

关于证书的,在这一篇文章

上面的都修改之后,先启动后端地址,然后再启动nginx就好了。不出意外的话就能在浏览器中打开你的项目了,快去体验体验吧。