A
A
Akmal Kamalov2018-12-03 04:48:50
Nginx
Akmal Kamalov, 2018-12-03 04:48:50

How to proxy to a different WebSocket's port in Nginx?

There is an application on the server, it listens on port 7777 and waits for a connection via ws://
Briefly about how it should work:
Browser -> Nginx(HTTPS) -> WS Server (here we want not to use a certificate, which is why such troubles)
The problem is that for some reason, when sending data to the server, only part of the messages from JS
5c048a45c9fb9864508454.png5c048a6e06b19184349849.png
comes in: Always 1 letter from the message comes, which is very strange.
I tried to run all the same on a local Windows machine, everything works as it should.
Launched in c# using websocket-sharp

WebSocketServer srv = new WebSocketServer(7777);
    srv.AddWebSocketService<MyClient>("/ws");//сюда должен перенаправлять proxy_pass
    srv.Start();
    Console.WriteLine("Server is listening......");

    //простой listener с выводом данных
    class MyClient : WebSocketBehavior
    {

        protected override void OnOpen() {  Write("Client Connected!", ConsoleColor.Green); }
        protected override void OnClose(CloseEventArgs e) {  Write("Close connection: "+ e.Reason, ConsoleColor.Red); }
        protected override void OnError(ErrorEventArgs e) { Write("Error: "+e.Message, ConsoleColor.DarkRed, ConsoleColor.Gray);  }
        protected override void OnMessage(MessageEventArgs e) { Write(e.Data); }
     }

Simple JS client:
var socket = new WebSocket("wss://мой-сайт/Game");
    socket.onopen = function() {
       console.log("Соединение установлено.");
       			activeBtns(false);
    };

    socket.onclose = function(event) {
      if (event.wasClean) {
       console.log('Соединение закрыто чисто');
      } else {
       console.log('Обрыв соединения'); // например, "убит" процесс сервера
      }
       console.log('Код: ' + event.code + ' причина: ' + event.reason);
      activeBtns(true);
    };

    socket.onmessage = function(event) {
       console.log("Получены данные ");
       console.log(event.data);
    };

    socket.onerror = function(error) {
       console.log("Ошибка " + error.message);
      activeBtns(true);
    };
    activeBtns();
    sendData = function(){
      socket.send("test message");
    };

On the server (OS: Ubuntu) there is Nginx with settings (installed clean v1.14.1):
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
  worker_connections 768;
  # multi_accept on;
}

http {
  sendfile on;
  keepalive_timeout 604800;
  proxy_connect_timeout 604800;
  proxy_send_timeout 604800;
  proxy_read_timeout 604800;

  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;

  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;
}

#конфиг моего домена:
server {
  listen       443 ssl;
  server_name  мой-сайт; #тут мой домен
  
  access_log /etc/nginx/logs/log.access;
  error_log /etc/nginx/logs/log.error error;
   
  ssl on;
  ssl_certificate /etc/ssl/certs/cert.pem;
  ssl_certificate_key /etc/ssl/private/cert.key;

  client_max_body_size 1M;
  client_body_buffer_size 1M;

  location / {
      root /var/www/мой-сайт/html;
      index  index.html index.htm;
  }

  location /Game {
    proxy_pass  http://мой-сайт:7777/ws;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Akmal Kamalov, 2018-12-04
@neroxt

The problem is in the server, I don’t know what exactly yet, but putting node.js everything worked

D
Dasha Tsiklauri, 2018-12-03
@dasha_programmist

it works like this for me, but only the server on Go:

map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
}
location = /ws {
            proxy_pass http://api-server:8088/ws;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question