【问题标题】:Angular 2 - TCP ConnectionAngular 2 - TCP 连接
【发布时间】:2021-04-13 05:53:46
【问题描述】:

我正在尝试建立从 Angular 11.2.5 到仅接受通过 IP 的 TCP 连接的本地设备(物理、硬件)的 tcp 连接。

当我在 Node 中使用 net 包时,我可以成功地与设备建立 TCP 连接。由于该软件包在 Ng 中不可用,因此我尝试为 Ng 使用 socket.io-client v4.0.1 软件包,但无法使其正常工作。

这是我对socket.io-client 的测试连接代码,它不起作用:

const {io} = require('socket.io-client');
const ip_address = '127.0.0.1';
const port = '5555';
const socket = io(`${ip_address}:${port}`);
socket.connect();

socket.on('connect', () => {
    console.log('connected');
    console.log(socket.connected, socket.id);
});

// also tried the below, did not connect as well
const socket = io.connect(`${ip_address}:${port}`);

控制台中没有错误信息

如何在 Angular 中建立 TCP 连接?

【问题讨论】:

  • 有人可以确认是否可以从 Ng 进行 tcp 调用吗?
  • 试试 rxjs 套接字
  • 控制台有错误信息吗?
  • 我相信有足够的例子
  • 定义'不起作用'。

标签: angular tcp socket.io


【解决方案1】:

更新:对不起,我最后错过了硬件设备...简短的回答是,浏览器不能直接连接到硬件设备套接字。因此,作为一种解决方法,您需要另一个软件或桥接器来调解浏览器和硬件设备之间的数据,如下所示...


问题是您的设备套接字无法理解客户端浏览器上的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);
  }

}

【讨论】:

  • 谢谢,很快就会对此进行测试,但要指出,根据 OP,TCP 连接需要建立到在其 IP 上接受 TCP 请求的物理硬件设备(一旦它位于本地网络上)。此设备未运行 socket.io 服务器,因此我无法发布“服务器端”代码。与设备的 TCP 连接确实通过“net”包在 Node 中工作。会报告的,谢谢。
  • 我想我明白了,问题是这是一个网络套接字..你需要把它桥接起来..
  • 好的,有一个 JS 版本的 websockify,但主要问题是:这在 Ng 中是否可以工作而无需通过 Node ?如果是这样,您能否更新您的帖子以反映除了您的 socket-io 代码之外为 websockify 设置的 Ng 吗?
  • 如果这对你有用,请标记为回答/赞成
  • @pete19 您无法直接从浏览器连接到 TCP,因此您的应用需要一个后端来处理它与设备之间的通信。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2012-11-11
  • 2011-07-19
  • 2019-01-28
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多