0


node搭建本地https和wss服务(SSL证书安全)

node 后台 app.js配置

const express = require('express') //加载express资源
const bodyParser=require("body-parser")//一个Express中间件,用于解析HTTP请求体,获得请求的数据

const app = express() //返回一个express服务器对象
const https = require('https')
const fs = require('fs')
const path = require('path');
const logger=require("morgan");//日志模块
const favicon=require("serve-favicon") //用于设置和提供 favicons(网页标签图标)。
const WebSocket = require('ws')

//导入ajaxRouter这个路由
const route=require("./routes/backmtage/ajaxRouter")
const route1=require("./routes/appoet/ajaxRouter");

// 日志模块放在最上方
app.use(logger("dev"))//调用日志,配置为dev(开发)模式

// 使用bodyParser应该在路由前
// extended:false:表示使用系统模块query string来处理数据
// extended:true 表示使用第三方模块qs来处理
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

//使用路由,放在静态资源路径前面
app.use(route)
app.use(route1)

//设置静态资源路径
//__dirname指向当前文件的根目录
app.use(express.static(__dirname+"/public"))
//设置小图标
app.use(favicon(__dirname+"/public/images/favicon.ico"))

//ssl证书
const options = {
    key:fs.readFileSync(path.join(__dirname,'./ssl/xxxxxx.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./ssl/xxxxxx.cn.pem'))
}

//创建https服务器
const httpsServer = https.createServer(options,app,(req,res)=>{
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' });
    res.end('This is a https server!\n') 
})

httpsServer.listen(8886, () => {
    // console.log('服务已开启8886');
    console.log('HTTPS Server is running on: https://xxxx.com:%s', 9999);
})

const wss = new WebSocket.Server(
    {
        server:httpsServer
    },
    ()=>{
        console.log('socket start');
    }
)
//建立连接
wss.on('connection',ws=>{
    //接收数据
    ws.on('message',data=>{
        console.log('received:%s',data);
    })

    ws.send('something')
})

服务启动后控制台输出:

测试:服务器连接

浏览器输入:https:xxxxx:端口 访问成功

测试wss

可以在这个网站websocket/ws/wss在线调试测试工具

发送消息 看服务端

参考:node搭建本地https和wss服务(SSL证书安全)_node ssl_jixhua的博客-CSDN博客

Node.js网络编程之WebSocket篇_node websocket_夜已如歌_ok的博客-CSDN博客

标签: websocket https 前端

本文转载自: https://blog.csdn.net/T3165919332/article/details/131569372
版权归原作者 T3165919332 所有, 如有侵权,请联系我们删除。

“node搭建本地https和wss服务(SSL证书安全)”的评论:

还没有评论