Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何服务于多角度+;带有socket.io的express.js应用程序_Javascript_Node.js_Express_Nginx_Websocket - Fatal编程技术网

Javascript 如何服务于多角度+;带有socket.io的express.js应用程序

Javascript 如何服务于多角度+;带有socket.io的express.js应用程序,javascript,node.js,express,nginx,websocket,Javascript,Node.js,Express,Nginx,Websocket,我有一个带有NGINX的服务器,它提供express.js(+socket.io)服务器和angular应用程序。这两个应用程序都有开发版本,所以它是由一个nginx配置提供的4个应用程序。在我将socket.io添加到express应用程序之前,所有配置都可以使用以下配置: user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 1024; } http {

我有一个带有NGINX的服务器,它提供express.js(+socket.io)服务器和angular应用程序。这两个应用程序都有开发版本,所以它是由一个nginx配置提供的4个应用程序。在我将socket.io添加到express应用程序之前,所有配置都可以使用以下配置:

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    client_max_body_size 100m;

    keepalive_timeout  65;

    ##
    # Logging Settings
    ##

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


    server {
        listen       4200;
        server_name  localhost;

        # dev version of angular app
        location /dev {
            expires    -1;
            add_header Pragma "no-cache";
            add_header Cache-Control "no-store, no-cache, must-revalicate, post-check=0 pre-check=0";
            alias      /home/user/angular_dev_app/frontend/dist/angular_dev_app;
            try_files  $uri $uri/ /index.html =404;
        }

        # dev version of express server
        location /dev/api {
            rewrite          ^\/dev/api(.*)$ $1 break;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_redirect   off;
            proxy_pass       http://localhost:9900/;
            proxy_set_header X-Real-IP $remote_addr;
        }

        # dev version of angular app
        location / {
            expires    -1;
            add_header Pragma "no-cache";
            add_header Cache-Control "no-store, no-cache, must-revalicate, post-check=0 pre-check=0";
            root       /home/user/angular_prod_app/frontend/dist/angular_prod_app;
            try_files $uri $uri/ /index.html =404;
        }

        # prod version of express server
        location /api {
            rewrite          ^\/api(.*)$ $1 break;

            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_redirect   off;
            proxy_pass       http://localhost:9901;
            proxy_set_header X-Real-IP $remote_addr;
        }

        gzip on;
        gzip_disable "msie6";
    }

    include servers/*;
}
但在我将socket.io逻辑添加到ExpressApp之后,它的行为非常奇怪。 除插座外的所有连接都可以正常工作。如果我在没有nginx的情况下运行express和angular应用程序,socket.io请求也可以正常工作。但当我使用nginx从远程服务器运行服务器时,它开始只在('connecting',…)上被调用,并忽略路由处理程序发出的任何消息

后端 express.js应用程序: app.routes.js 前端 socket.service.ts
我的NGINX配置有问题吗?或者我设置的服务器(或客户端应用程序)不正确?

能否添加
proxy\u http\u版本1.1@RolandStarke添加了,但它仍然不能工作:(您的屏幕截图显示您的websocket连接正常。您的问题与nginx的配置无关。您是否在@RolandStarke?@Maxisagaydachny建议的更改后重新启动了nginx?@Maxisagaydachny当然是。您知道问题的原因吗?我相信这与nginx有关,因为一切正常locally@MaximSagaydachny我发现在我调用
io.emit(…)
at
app.routes
时,没有连接到套接字的用户,但自从我连接到套接字后就没有断开连接。你可以添加
proxy\u http\u version 1.1;
@RolandStarke,但它仍然不能工作:(您的屏幕截图显示您的websocket连接正常。您的问题与nginx的配置无关。您是否在@RolandStarke?@Maxisagaydachny建议的更改后重新启动了nginx?@Maxisagaydachny当然是。您知道问题的原因吗?我相信这与nginx有关,因为一切正常locally@MaximSagaydachny我发现,在我调用
io.emit(…)
at
app.routes
的时候,没有连接到套接字的用户,但自从我连接到它之后,就没有断开连接
const io = require("socket.io").listen(server);

io.origins("*:*");


io.on("connection", socket => {
    socket.emit("Hello", `Hello, ${socket.handshake.session.passport.user}`); # gets to frontend locally and remotely

    socket.on("sendImage", (image) => {
        console.log(image);
        io.emit("addImage", image);
    });
});

app.use(require("app.routes")(io));

module.exports = io => {
    const router = express.Router();

    router.post(
        "/some-url",
        (req, res, next) => {
              const result = 'something';
              io.emit("sendImage", result); # gets to frontend only locally

              res.status(200).send({ body: [] });
        }
    );

    return router;
};
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import * as io from "socket.io-client";
// import { SocketIOClient } from "socket.io-client";

import { ConfigService } from "./config.service";

@Injectable()
export class SocketService {
    private socket: SocketIOClient.Socket;
    private wsOriginUrl: string;
    private wsPath: string;

    constructor(private environment: ConfigService) {
        this.wsOriginUrl = this.environment.config.wsOriginUrl;
        this.wsPath = this.environment.config.wsPath;

        this.socket = io(this.wsOriginUrl, {
            path: this.wsPath,
            transports: ["websocket"]
        });
        this.socket.on("connect", () => this.connected());
        // this.socket.on("disconnect", () => this.disconnected());
        this.socket.on("error", (error: string) => {
            console.log(`ERROR: "${error}" (${this.wsOriginUrl})`);
        });
    }

    public connect() {
        this.socket.connect();
    }

    public disconnect() {
        this.socket.disconnect();
    }

    public emit(chanel, message) {
        return new Observable<any>(observer => {
            console.log(`emit to ${chanel}:`, message); // is called for 'addImage' when both are localhost only
            this.socket.emit(chanel, message, function(data) {
                if (data.success) {
                    observer.next(data.msg);
                } else {
                    observer.error(data.msg);
                }
                observer.complete();
            });
        });
    }

    public on(event_name) {
        // console.log(`listen to ${event_name}:`);
        return new Observable<any>(observer => {
            this.socket.off(event_name);
            this.socket.on(event_name, data => {
                observer.next(data);
            });
        });
    }

    private connected() {
        console.log("Connected"); // is called when both are localhost or angular local + express remote
    }

    private disconnected() {
        console.log("Disconnected");
    }
}
@Injectable()
export class ImagesService {
    private backendApiUrl: string;

    constructor(
        private http: HttpClient,
        private environment: ConfigService,
        private socketService: SocketService
    ) {
        this.backendApiUrl = environment.config.origin;
    }

    public getServerSentImage(): Observable<any> {
        return this.socketService.on("addImage").pipe(
            map(response => {
                console.log(response);
                return response;
            })
        );
    }
}
@Component({
    selector: "app-page",
    templateUrl: "./page.component.html",
    animations: [fadeInOutTransition],
    styleUrls: ["./page.component.scss"]
})
export class PageComponent implements OnInit, OnDestroy {
    private serverSentImageSubscription: Subscription = new Subscription();

    constructor(
        private imagesService: ImagesService,
    ) {
    }
    ngOnInit() {
        this.serverSentImageSubscription = this.imagesService
            .getServerSentImage()
            .subscribe(
                image => {
                    this.addImage(image);
                },
                error => {
                    console.error(error);
                }
            );
    }

    ngOnDestroy() {
        this.serverSentImageSubscription.unsubscribe();
    }

    public addImage(image: any) {
        // do something
    }
}