前端js需要连接后端c#的wss服务

背景
前端js需要连接后端wss服务

前端:js
后端:c# - 控制台搭建wss服务器

步骤1

wss需要ssl认证,所以需要个证书,随便找一台linux的服务器(windows的话,自己安装下openssl即可),一般都有安装openssl的工具,利用它来生成一份证书

1、最好是cd到一个自定义目录下操作,后面生成的3个文件都在这里的

生成.key文件,要求输入一个自定义的密码,输入2遍,至少4位,假设这里我们输入的是:123456,因为后面移除key文件的密码时需要
openssl genrsa -des3 -out server.key 2048
2、生成.crt文件,默认给他10年有效期,随便霍霍造,会提示输入密码,也就是上面key的密码,123456,后面按需要会提示输入一些信息,自己酌情即可,想省略的话输入.即可
openssl req -new -x509 -key server.key -out server.crt -days 3650
...
Common Name (eg, your name or your server's hostname) []:xl
这一项最好是写点东西,安装的时候会提示证书颁发给和颁发者,后续如果在windows里面导的话,更容易找到,当然,不写也没有关系的
...
3、生成.pfx文件(上面2个主要是前端nginx配置需要,pfx这个主要是给c#用的,用来加载到程序里,它相当于是key和crt的集合体)
openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt
会提示输入密码之类的,
Enter pass phrase for server.key: 这个是上面key的密码,也就是123456
Enter Export Password: 这个是区别key的,打开pfx的密码,为了放置错乱,最好也设置成123456
Verifying - Enter Export Password: 确认输入一次pfx的密码
完事后,目录下就生成3个文件了应该
4、取消掉key文件的密码限制,不然nginx每次启动都会要求输入密码的
openssl rsa -in server.key -out server.key
会提示输入密码,输入即可,123456嘛,完了后面都不用输入密码了,我在想是不是可以key生成了就把密码给他移除掉,后面就不用再输入那么多次密码了,可以试试后面...

步骤2

nginx配置ssl

打开nginx配置文件如下:

server {

listen 443 ssl; # 端口看你心情,端口后面 ssl必须要加上

server_name localhost;

ssl_certificate F:\SourceCode\XL\VUE\dccsplayer\dist\ssl\server.crt; #指定一下你的证书路径

ssl_certificate_key F:\SourceCode\XL\VUE\dccsplayer\dist\ssl\server.key; #指定一下你的key路径

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X_FORWARDED_PROTO https;

proxy_set_header X-Forwarded-For $remote_addr;

proxy_set_header Host $host;

proxy_redirect off;

proxy_set_header Upgrade $http_upgrade;

proxy_set_header Connection "upgrade";

location / {

root F:\SourceCode\XL\VUE\dccsplayer\dist; #这个是我的工程导出的目录,替换成你的

index index.html index.htm;

配置让Vue Router处理路由

#try_files uri uri/ /index.html;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

}

}

}

保存后,重启一下nginx,测试下网站能不能访问了

步骤3

c#代码构建wss服务,Nuget,搜索安装:Fleck

复制代码
 1 using Fleck;
 2 using Microsoft.VisualBasic;
 3 using System.Diagnostics;
 4 using System.Reflection;
 5 using System.Security.Cryptography.X509Certificates;
 6 
 7 Console.WriteLine("Hello, World!");
 8 
 9 string exePath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
10 
11 var location = "wss://0.0.0.0:8972";
12 WebSocketServer server = new WebSocketServer(location);
13 
14 // ssl配置
15 server.Certificate = new X509Certificate2(Path.Combine(exePath, "xl", "server.pfx"), "123456");  //配置pfx证书的目录,且配置打开密码
16 server.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
17 
18 //出错后进行重启
19 server.RestartAfterListenError = true;
20 //开始监听
21 server.Start(socket =>
22 {
23     socket.OnOpen = () =>   //连接建立事件
24     {
25         Console.WriteLine($"有新的连接");
26     };
27     socket.OnClose = () =>  //连接关闭事件
28     {
29         Console.WriteLine($"有连接被关闭");
30     };
31     socket.OnMessage = message =>  //接受客户端网页消息事件
32     {
33         Console.WriteLine($"接受客户端网页消息事件 -> {message}");
34     };
35     socket.OnError = exp =>
36     {
37         Console.WriteLine($"有连接被意外中断");
38     };
39 });
40 Console.WriteLine("任意键停止...");
41 Console.ReadLine();
42 server.Dispose();

前端js

复制代码
const ws = new WebSocket('wss://10.6.30.127:8972')
    ws.onopen = () => {
      console.log('握手成功')
      if (ws.readyState == 1) {
        console.log('连接成功')

        setInterval(() => {
          ws.send(`测试发送:${new Date()}`)
        }, 1000)
      }
    }
    ws.onmessage = (msg) => {
      console.log('msg', msg)
    }
    ws.onerror = (err) => {
      console.info(err)
    }

整体效果图:

连接的时候有个警告,不知道为啥还,有知道朋友可以告知下,但是不影响使用