Ubuntu 20.04配置Nginx Websocket

前提是ubuntu20.04系统安装好了,并安装了ssh,openssl,这些是系统自带的。

1. Websocket 简介

WebSocket 是一种基于 TCP 连接的全双工通信的协议,其工作在应用层,建立连接的时候通过复用 Http 握手通道,完成 Http 协议的切换升级,即切换到 WebSocket 协议,协议切换成功后,将不再需要客户端发起请求,服务端就可以直接主动向客户端发送数据,实现双向通信。

和 Http 相比,WebSocket有以下优点:

  • WebSocket 是双向通信协议,可以双向发送或接受信息。HTTP是单向的,只能由客户端发起请求时,服务器才能响应,服务器不能主动向客户端发送数据。
  • WebSocket 可以和 HTTP Server 共享相同端口。
  • WebSocket 协议可以更好的支持二进制,可以直接传送二进制数据。
    同时WebSocket协议的头部非常小,服务器发到客户端的数据包的包头,只有2~10个字节(取决于数据包的长度),客户端发送服务端的包头稍微大一点,因为其要进行掩码加密,所以还要加上4个字节的掩码。总得来说,头部不超过14个字节。
    支持扩展,用户可以扩展协议实现自己的子协议。

2.更新系统

apt-get update
apt-get upgrade

3.安装后端服务nodejs npm ws

apt-get install nodejs npm
npm install ws

4.安装测试程序

apt install wscat
atp install curl

5.后端 websocket 服务部署

后端使用8010端口

服务端代码

// app.js 文件
// 导入相关模块
const WebSocket = require('ws');
const  http = require('http');

// 使用 http 模块创建的 http.Server
httpserver = http.createServer(function (request, response) {
    // 发送 HTTP 头部
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});

    // 发送响应数据 "Hello World"
    response.end('Http Message: Hello World\n');
}).listen(8010); // 监听 80 端口, 根据 http.Server 创建 WebSocketServer


//创建 WebSocketServer
const WebSocketServer = WebSocket.Server;
const wss = new WebSocketServer({
    server: httpserver //根据 http.Server 创建 WebSocketServer
});

wss.on('connection', function (ws) {
    ws.send("Websocket Send: Hello World")  //客户端连接成功后立即向客户端发送一条消息
    console.log(`WebSocket connection()`);
    ws.on('message', function (message) {  //收到客户端的消息
        console.log(`Websocket Received: ${message}`);
        ws.send('Server received from client: ' + message);
    })
});

console.log('WebSocket and Http Server started at port 8010...');

运行后端服务

root@linux:/home/# nodejs app.js &
[1] 34560
root@linux:/home/# WebSocket and Http Server started at port 8010...

6.安装nginx

root@linux:~# echo "deb http://security.ubuntu.com/ubuntu bionic-security main" | sudo tee -a /etc/apt/sources.list.d/bionic.list
deb http://security.ubuntu.com/ubuntu bionic-security main
root@linux:~# 
root@linux:~# sudo apt update
Hit:1 https://mirrors.tuna.tsinghua.edu.cn/ubuntu focal InRelease                                                           
Hit:2 https://mirrors.tuna.tsinghua.edu.cn/ubuntu focal-updates InRelease                                                   
Hit:3 https://mirrors.tuna.tsinghua.edu.cn/ubuntu focal-backports InRelease    
Hit:4 https://mirrors.tuna.tsinghua.edu.cn/ubuntu focal-security InRelease     
Get:5 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]    
Get:6 https://nginx.org/packages/ubuntu xenial InRelease [4,354 B]          
Get:7 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [2,471 kB]
Get:8 http://security.ubuntu.com/ubuntu bionic-security/main Translation-en [428 kB]
Fetched 2,992 kB in 5s (617 kB/s)                              
Reading package lists... Done
Building dependency tree       
Reading state information... Done
All packages are up to date.
root@linux:~# apt-cache policy libssl1.0-dev
libssl1.0-dev:
  Installed: (none)
  Candidate: 1.0.2n-1ubuntu5.10
  Version table:
     1.0.2n-1ubuntu5.10 500
        500 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages
root@linux:~# apt-get install libssl1.0-dev
...
root@linux:~# apt-get install nginx
root@linux:~# service nginx start
root@linux:~# curl 192.168.215.80
<title>Welcome to nginx!</title>
...

7.配置nginx

生成自签名证书

root@linux:~# mkdir ssl
root@linux:~# cd ssl/
root@linux:~/ssl# 
root@linux:~/ssl# 
root@linux:~/ssl# openssl genrsa -out private.key 4096
Generating RSA private key, 4096 bit long modulus (2 primes)
...................................................................................................++++
..........................................++++
e is 65537 (0x010001)
root@linux:~/ssl# ls
private.key
root@linux:~/ssl# openssl req -new -key private.key -out server.csr
root@linux:~/ssl# ls
private.key  server.csr
root@linux:~/ssl# openssl req -x509 -days 365 -key private.key -in server.csr -out server.crt
root@linux:~/ssl# ls
private.key  server.crt  server.csr
root@linux:~/ssl# openssl x509 -noout -text -in server.crt

private.key server.crt 这两个就是需要的证书文件。

Nginx 配置文件

Nginx 监听 80 端口用于 Http 和 ws 服务,监听 443 端口用于 Https 和 wss 服务。wss 就是加密的 ws 服务。

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

upstream websocket {
    server 127.0.0.1:8010;
}

server {
    listen       80;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
		
		proxy_http_version 1.1;
		proxy_pass http://websocket;
		proxy_set_header Upgrade $http_upgrade;
		proxy_set_header Connection "upgrade";
    }

    #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   /usr/share/nginx/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;
    #}
}

server {
    	listen 443 ssl;
    	server_name yourdomain.cn www.yourdomain.cn;    

    	ssl_certificate "/root/ssl/server.crt";   
    	ssl_certificate_key "/root/ssl/private.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout 5m;
		ssl_ciphers HIGH:!aNULL:!MD5;
		ssl_prefer_server_ciphers on;
		ssl_protocols SSLv3 SSLv2 TLSv1 TLSv1.1 TLSv1.2;
		ssl_verify_client off;
		add_header Access-Control-Allow-Origin *;

	    error_page   500 502 503 504  /50x.html;
	    location = /50x.html {
	        root   /usr/share/nginx/html;
	    }

    	location / {
			        root   /usr/share/nginx/html;
			        index  index.html index.htm;    	
			        try_files $uri $uri/ /index.html;	
					
					proxy_http_version 1.1;
					proxy_pass http://websocket; 
					proxy_set_header Upgrade $http_upgrade;
					proxy_set_header Connection "Upgrade";
		}
	}

启动 Nginx 服务

nginx -t
service nginx start

8. 验证

测试 Http & Https 连接

root@linux:/home/# curl -i https://192.168.215.80 -k
HTTP/1.1 200 OK
Server: nginx/1.20.1
Date: Sat, 26 Nov 2022 11:05:48 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *

Http Message: Hello World
root@linux:/home/# 
root@linux:/home/# curl -i http://192.168.215.80 
HTTP/1.1 200 OK
Server: nginx/1.20.1
Date: Sat, 26 Nov 2022 11:05:55 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive

Http Message: Hello World

测试 ws & wss 连接

使用curl
进行https连接时,加-k ,由于是自签名,表示不进行验证。

root@linux:/home/# curl -i --header "Upgrade: websocket" --header "Sec-WebSocket-Key: MlRAR6bQZi07587UD4H8oA==" --header "Sec-WebSocket-Version: 13" https://192.168.215.80 -k
HTTP/1.1 101 Switching Protocols
Server: nginx/1.20.1
Date: Sat, 26 Nov 2022 11:07:54 GMT
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Accept: iURIl3uIT+tsPMmZ0x1IVH7EL98=

^C
root@linux:/home/# curl -i --header "Upgrade: websocket" --header "Sec-WebSocket-Key: MlRAR6bQZi07587UD4H8oA==" --header "Sec-WebSocket-Version: 13" http://192.168.215.80
HTTP/1.1 101 Switching Protocols
Server: nginx/1.20.1
Date: Sat, 26 Nov 2022 11:08:03 GMT
Connection: upgrade
Upgrade: websocket
Sec-WebSocket-Accept: iURIl3uIT+tsPMmZ0x1IVH7EL98=

使用wscat
进行https连接时,加-n,由于是自签名,表示不进行验证。

root@linux:/home/# wscat --connect ws://192.168.215.80
Connected (press CTRL+C to quit)
< Websocket Send: Hello World
> 12
< Server received from client: 12
> 3
< Server received from client: 3
> root@linux:/home/# wscat --connect wss://192.168.215.80 -n
Connected (press CTRL+C to quit)
< Websocket Send: Hello World
> 12
< Server received from client: 12
> 12
< Server received from client: 12
> 3
< Server received from client: 3
> 

–全文完–
参考文档:https://blog.csdn.net/bluebird_shao/article/details/123873452
http://www.195440.com/1585
https://www.modb.pro/db/436209
https://www.cnblogs.com/mfrbuaa/p/5413786.html
https://developer.aliyun.com/article/345476
https://www.cnblogs.com/tomtellyou/p/12164226.html

你可能感兴趣的:(操作系统,ubuntu,nginx,websocket)