gpt4 book ai didi

node.js - 套接字io,node.js

转载 作者:太空宇宙 更新时间:2023-11-03 22:07:34 25 4
gpt4 key购买 nike

我会尽力解释自己!

我有一个node.js服务器,我想添加socket.io。我设法让它在 http 上运行,但在 https 上运行时遇到一些问题。

服务器:

var express = require('express');
var app = express();
var fs = require('fs');


var key = fs.readFileSync('mydomain.key');
var cert = fs.readFileSync( 'mydomain.crt' );

var options = {
key: key,
cert: cert
};

var https = require('https');
var io = require("socket.io")(https);
var cors = require('cors')

var server = https.createServer(options, app).listen(443);

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", 'domain');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Credentials', true);
next();



server.on('error', function (e) {
console.log(e);
});

io.on('connection',function(socket){
console.log("A user is connected");
socket.on('add reserva',function(status){
//io.sockets.emit('update reserva', status);
add_reserva(status,function(res){
if(res){io.sockets.emit('update reserva', status);}
else {io.sockets.emit('error');}
});
});
});

**And the client code:**

$(document).ready(function(){
var socket = io("https://151.236.63.10:443");
$("#add_status").click(function(){
socket.emit('add reserva',$("#comment").val());
});
socket.on('update reserva',function(msg){
new Noty({
type: 'success',
layout: 'topRight',
text: msg
}).show();
});
});
});

此外,如果我可以用代码做得更好,我将不胜感激任何建议

最佳答案

好的,我会给你一个重写,以获得更清晰的内容。希望能帮助到你。

const express = require express();
const app = express();
const https = require('https');
const fs = require('fs');

const config = require('./config'); //--> config file

var options = {
key: fs.readFileSync('mydomain.key'),
cert: fs.readFileSync( 'mydomain.crt' )
};

const secureServer = https.createServer(options,app).listen(config.portHTTPS);

const io = require('socket.io')(secureServer) // you can add options for socket here

关于node.js - 套接字io,node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51282850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com