更新:对不起,我最后错过了硬件设备...简短的回答是,浏览器不能直接连接到硬件设备套接字。因此,作为一种解决方法,您需要另一个软件或桥接器来调解浏览器和硬件设备之间的数据,如下所示...
问题是您的设备套接字无法理解客户端浏览器上的websocket“框架”数据,您需要克服/“桥接”或“代理”该连接到设备上。
您必须使用类似Websockify/socket.io 服务器的东西作为代理在 websocket 客户端和非 websocket 服务器之间桥接来克服 websocket。
So, the clients webscoket doesn't communicate with the device directly, but with a websockify server instead.
Subsequently websockify unpacks/unwraps the framed data from the Websocket data stream and forwards it to your device. Viceversa - the response from the device is packed into WebSocket frames forwarded to client.
请同时发布Client & Server Code & Console,这将有助于我们更轻松地调试。
安装包,CLI 就这样
npm install socket.io-client
npm install @types/socket.io-client
然后导入库
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs/Observable';
import * as Rx from 'rxjs/Rx';
import { environment } from '../environments/environment';
检查客户端配置/设置
let hostname = window.location.hostname;
// you can change the undefined below to server if its not your local
let url = ( hostname === 'localhost' ) ? `${window.location.protocol}//${hostname}:8080` : undefined;
const config: SocketIoConfig = { url: url, options: {} };
检查服务器配置
const port = process.env.PORT || 8080;
const server = http.Server(app);
const io = require( 'socket.io' )( server );
server.listen( port, () => { console.log( `listening on port: ${port}`) } );
然后使用observers 的服务来处理轻松发送和接收的消息不错的示例here ...
@Injectable()
export class WebsocketService {
// Our socket connection
private socket;
constructor() { }
connect(): Rx.Subject<MessageEvent> {
// If don't use environment variables, you can hard code `environment.ws_url` as `http://localhost:5000`
this.socket = io(environment.ws_url);
// Observable to observe incoming messages from server socket.io server.
let observable = new Observable(observer => {
this.socket.on('message', (data) => {
console.log("Received message from backend Websocket Server")
observer.next(data);
})
return () => {
this.socket.disconnect();
}
});
// Observer listens to messages, other client components and send messages back to our socket server using `next()`
let observer = {
next: (data: Object) => {
this.socket.emit('message', JSON.stringify(data));
},
};
// return a Rx.Subject its a combination of observer and observable.
return Rx.Subject.create(observer, observable);
}
}