尝试使用rxjs webSocket使WebSocket工作
我设置了一个节点服务器,该节点服务器目前不会出现任何错误,但是不会向服务器或连接的用户发送消息
当我使用'ws://echo.websocket.org/'时似乎效果更好,我看到回显了消息,但是,在其他打开的浏览器中,我看不到发送的消息,基本上没有通信用户之间,应该被订阅到网络套接字
我想要的是在用户之间传递简单信息的简单方法
index.js
var express = require('express');
var WebSocketServer = require('websocket').server;
var app2 = express()//There is already another app var for main app server
var server2 = http.createServer(app2);
var server2 = app2.listen(8081, function () {
console.log((new Date()) + ' Server is listening on port 8081');
})
wsServer = new WebSocketServer({
httpServer: server2,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
if (origin === 'http://localhost:1234'){
return true;
}
// put logic here to detect whether the specified origin is allowed.
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept(null, request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
// console.log(message)
if (message.type === 'utf8') {
console.log('Received Message from: ' + connection.remoteAddress);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
在我的客户端套接字服务中:
import { Injectable } from '@angular/core';
import { Observable } from '../../../node_modules/rxjs';
@Injectable()
export class SocketService {
socket$ = Observable.webSocket( 'ws://localhost:8081');
// 'ws://echo.websocket.org/'
constructor() {
this.connectToSocket()
}
connectToSocket(){
this.socket$.subscribe(
(message) => console.log('message received: ' + message),
(err) => console.log(err),
() => console.log('complete')
);
}
}
从另一个组件发送消息,我使用:
this.socketService.socket $ .next(JSON.stringify('test'))
答案 0 :(得分:1)
根据WebSocket-Node
(https://github.com/theturtle32/WebSocket-Node/blob/master/docs/WebSocketServer.md)的文档,必须在继续握手之前以编程方式接受每个连接。
您可以将服务器配置的autoAcceptConnections
选项设置为true
,如下所示:
const wss = new WebSocketServer({ httpServer: server2, autoAcceptConnections: true });
如果确实有自定义请求检查要求,则可以在accept
处理程序中使用reject
或request
,如下所示:
request.accept('chosen-protocol', 'accepted-origin')
或
request.reject()