O
O
Ostap Likhodeev2019-09-25 22:18:13
Node.js
Ostap Likhodeev, 2019-09-25 22:18:13

Why does it not connect to the websocket from the outside, but does it connect locally?

Here is the server itself, the certificates are all ports are open, this is exactly how the PHP websocket works on this port.
I try the server on node.js locally, the connection goes on and everything works, but it doesn’t connect to it from the boarding school, why is that?

var mysql = require('mysql');


var fs = require( 'fs' );
const express = require('express'),
    app = express(),
    https = require('https').createServer({key: fs.readFileSync('../crt/private.key'),cert: fs.readFileSync('../crt/domain_name.crt'),ca: fs.readFileSync('../crt/chain.crt'),requestCert: false,rejectUnauthorized: false},app),
    io = require('socket.io')(https);

const host = 'site.ru'; //Тут адрес моего сайта
const port = 441;

let clients = [];

io.on('connection', socket => {
  //Получение инфы о пользователи
    var regexp = /user=([^&]+)/;
    var GetValue = '';
    if (!!regexp.exec(socket.handshake.url))
        GetValue = regexp.exec(socket.handshake.url)[1];
    var arr =GetValue.split('_'),
        userId =arr[0],
        room=arr[1];
    console.log({'connected':userId,"roomNew":room});
    clients.push(socket.id);
    socket.emit('message', {"imid":userId,"roomNew":room});
    var conn = mysql.createConnection({
        database: 'game',
        host: "localhost",
        user: "root",
        password: "pass"
    });
    var sql1 = "UPDATE `user` SET `ontime`=1 WHERE `uid` ="+userId+"";

    conn.query(sql1, function(err, results) {
        if (err) throw err;
        console.log("Online-"+userId);
    });
    conn.end();
    //Отправка сообщений всем
    socket.on('message', message => io.sockets.emit('message', message));


    //Отключение пользователя
    socket.on('disconnect', () => {
        var conn = mysql.createConnection({
            database: 'game',
            host: "localhost",
            user: "root",
            password: "Kx2H5LdJumlqzkxd"
        });
        var sql1 = "UPDATE `user` SET `ontime`=0 WHERE `uid` ="+userId+"";

        conn.query(sql1, function(err, results) {
            if (err) throw err;
            console.log("Ofline-"+userId);
        });
        conn.end();
        clients.splice(clients.indexOf(socket.id), 1);
        socket.emit({"discconnected":userId,"roomOut":room});
        console.log({"discconnected":userId,"roomOut":room});
    })
});

app.use(express.static(__dirname));

app.get('/', (req, res) => res.render('index'));

//получение количества активных клиентов
app.get('/clients-count', (req, res) => {
    res.json({count: io.clients().server.engine.clientsCount})
});

//отправка сообщения конкретному клиенту по его id
app.post('/client/:id', (req, res) => {
    if (clients.indexOf(req.params.id) !== -1) {
        io.sockets.connected[req.params.id].emit('private message', `Message to client with id ${req.params.id}`);
        return res.status(200).json({ message: `Message was sent to client with id ${req.params.id}` })
    } else return res.status(404).json({ message: 'Client not found' })
});

https.listen(port, host, () => console.log(`Server listens https://${host}:${port}`));

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question