R
R
Raydon122021-07-26 15:23:25
Node.js
Raydon12, 2021-07-26 15:23:25

How to combine work with websocket and http protocols?

Hello, I have a node.js server that uses socket.io and http library. I am new to the backend and would like to ask you: let's say we take the example of some forum. We have private messages, a profile page, a list of topics you replied to and stuff like that. My question is: how do I combine events that require instant updates with regular post and get requests? That is, should I make a separate server for sockets, or what? I'm a little confused on this issue. Really looking forward to the answer!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kr_ilya, 2021-07-26
@kr_ilya

In short , you
run the http server on one port.
socket.io server running on a different port.
Then through nginx, for example, you proxy them to different addresses.
For example

server.js

//http
const express = require('express');
const server = require('http')
var app = express();
var server = server.Server(app);
server.listen(3000);

//socket
Socket.io = require('socket.io')(3001, { path: '/', });


Server section of nginx config

# Для стандартных пост гет запросов (запросы, естественно, будут на site/api/)
location /api/ {
    expires $expires;

    proxy_redirect                      off;
    proxy_set_header Host               $host;
    proxy_set_header X-Real-IP          $remote_addr;
    proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_read_timeout          30m;
    proxy_connect_timeout       30m;
    send_timeout                30m;
    proxy_pass                          http://127.0.0.1:3000/; # set the adress of the Node.js instance here
}

# Для сокетов
location /socket/ {

    expires $expires;

    proxy_redirect                      off;
    proxy_set_header Host               $host;
    proxy_set_header X-Real-IP          $remote_addr;
    proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_set_header                    Upgrade $http_upgrade; #для сокетов
    proxy_set_header                    Connection "upgrade"; #для сокетов
    proxy_http_version 1.1;
    proxy_read_timeout          30m;
    proxy_connect_timeout       30m;
    send_timeout                30m;
    proxy_pass                          http://127.0.0.1:3001; # set the adress of the Node.js instance here
    

    
    # proxy_ssl_server_name on;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question