Set websocket url to /ws

The routing is desided by protocol
This commit is contained in:
Oskar Hahn 2018-11-04 17:13:24 +01:00 committed by FinnStutzenstein
parent a2d736bae9
commit 8ee9fb1742
5 changed files with 18 additions and 37 deletions

View File

@ -11,7 +11,7 @@
"target": "http://localhost:8000", "target": "http://localhost:8000",
"secure": false "secure": false
}, },
"/ws/site/": { "/ws/": {
"target": "ws://localhost:8000", "target": "ws://localhost:8000",
"secure": false, "secure": false,
"ws": true "ws": true

View File

@ -1,5 +1,4 @@
import { Injectable, NgZone, EventEmitter } from '@angular/core'; import { Injectable, NgZone, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subject } from 'rxjs'; import { Observable, Subject } from 'rxjs';
import { MatSnackBar, MatSnackBarRef, SimpleSnackBar } from '@angular/material'; import { MatSnackBar, MatSnackBarRef, SimpleSnackBar } from '@angular/material';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
@ -76,13 +75,11 @@ export class WebsocketService {
/** /**
* Constructor that handles the router * Constructor that handles the router
* @param router the URL Router
* @param matSnackBar * @param matSnackBar
* @param zone * @param zone
* @param translate * @param translate
*/ */
public constructor( public constructor(
private router: Router,
private matSnackBar: MatSnackBar, private matSnackBar: MatSnackBar,
private zone: NgZone, private zone: NgZone,
public translate: TranslateService public translate: TranslateService
@ -117,11 +114,12 @@ export class WebsocketService {
} }
// Create the websocket // Create the websocket
const socketProtocol = this.getWebSocketProtocol(); let socketPath = location.protocol === 'https' ? 'wss://' : 'ws://';
const socketServer = window.location.hostname + ':' + window.location.port; socketPath += window.location.hostname + ':' + window.location.port + '/ws/';
const socketPath = this.getWebSocketPath(queryParams); socketPath += this.formatQueryParams(queryParams);
console.log('connect to', socketProtocol + socketServer + socketPath);
this.websocket = new WebSocket(socketProtocol + socketServer + socketPath); console.log('connect to', socketPath);
this.websocket = new WebSocket(socketPath);
// connection established. If this connect attept was a retry, // connection established. If this connect attept was a retry,
// The error notice will be removed and the reconnectSubject is published. // The error notice will be removed and the reconnectSubject is published.
@ -229,21 +227,15 @@ export class WebsocketService {
} }
/** /**
* Delegates to socket-path for either the side or projector websocket. * Formats query params for the url.
* @param queryParams
* @returns the formatted query params as string
*/ */
private getWebSocketPath(queryParams: QueryParams = {}): string { private formatQueryParams(queryParams: QueryParams = {}): string {
// currentRoute does not end with '/' let params = '';
const currentRoute = this.router.url;
let path: string;
if (currentRoute.includes('/projector') || currentRoute.includes('/real-projector')) {
path = '/ws/projector/';
} else {
path = '/ws/site/';
}
const keys: string[] = Object.keys(queryParams); const keys: string[] = Object.keys(queryParams);
if (keys.length > 0) { if (keys.length > 0) {
path += params =
'?' + '?' +
keys keys
.map(key => { .map(key => {
@ -251,17 +243,6 @@ export class WebsocketService {
}) })
.join('&'); .join('&');
} }
return path; return params;
}
/**
* returns the desired websocket protocol
*/
private getWebSocketProtocol(): string {
if (location.protocol === 'https') {
return 'wss://';
} else {
return 'ws://';
}
} }
} }

View File

@ -31,7 +31,7 @@ module.exports = function(config) {
'/apps/': 'http://localhost:8000/apps/', '/apps/': 'http://localhost:8000/apps/',
'/media/': 'http://localhost:8000/media/', '/media/': 'http://localhost:8000/media/',
'/rest/': 'http://localhost:8000/rest/', '/rest/': 'http://localhost:8000/rest/',
'/ws/site/': 'ws://localhost:8000/ws/site' '/ws/': 'ws://localhost:8000/'
} }
}); });
}; };

View File

@ -9,7 +9,7 @@ application = ProtocolTypeRouter({
# WebSocket chat handler # WebSocket chat handler
"websocket": AuthMiddlewareStack( "websocket": AuthMiddlewareStack(
URLRouter([ URLRouter([
url(r"^ws/site/$", SiteConsumer), url(r"^ws/$", SiteConsumer),
]) ])
) )
}) })

View File

@ -51,7 +51,7 @@ async def get_communicator():
nonlocal communicator # use the outer communicator variable nonlocal communicator # use the outer communicator variable
if query_string: if query_string:
query_string = "?{}".format(query_string) query_string = "?{}".format(query_string)
communicator = WebsocketCommunicator(application, "/ws/site/{}".format(query_string)) communicator = WebsocketCommunicator(application, "/ws/{}".format(query_string))
return communicator return communicator
yield get_communicator yield get_communicator
@ -181,7 +181,7 @@ async def test_with_user():
session.save() session.save()
scn = settings.SESSION_COOKIE_NAME scn = settings.SESSION_COOKIE_NAME
cookies = (b'cookie', '{}={}'.format(scn, session.session_key).encode()) cookies = (b'cookie', '{}={}'.format(scn, session.session_key).encode())
communicator = WebsocketCommunicator(application, "/ws/site/", headers=[cookies]) communicator = WebsocketCommunicator(application, "/ws/", headers=[cookies])
connected, __ = await communicator.connect() connected, __ = await communicator.connect()