angular - 在 Angular 中连接 WebSocket
问题描述
我在节点中有 WebSocket 连接,它工作正常。现在我想通过 rxjs websocket 在 Angular 中使用它,但我不知道如何解决连接问题。
const WebSocket = require('ws');
const ws = new WebSocket('wss://example.com');
ws.on('open', function open() {
// on connection, send our authentication request
ws.send(JSON.stringify({action: 'auth', key: apiKey, secret: apiSecret}));
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function incoming(data) {
console.log(data)
var msg = JSON.parse(data);
if (msg.type === 'status' && msg.status === 'authenticated') {
// if we got authentication confirmation, send subscribe event to the server
ws.send(JSON.stringify({action: 'subscribe', buckets: ['exampleBucket']}));
}
});
解决方案
监听来自服务器的消息
import { webSocket } from "rxjs/webSocket";
const subject = webSocket('wss://example.com');
subject.subscribe(
msg => console.log('message received: ' + msg), // Called whenever there is a message from the server.
err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
() => console.log('complete') // Called when connection is closed (for whatever reason).
);
向服务器推送消息
import { webSocket } from "rxjs/webSocket";
const subject = webSocket('wss://example.com');
subject.subscribe();
// Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
// since no connection was established!
subject.next({message: 'some message'});
// This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!
subject.complete(); // Closes the connection.
subject.error({code: 4000, reason: 'I think our app just broke!'});
// Also closes the connection, but let's the server know that this closing is caused by some error.
推荐阅读
- reactjs - 问题 chrome 内容安全策略反应扩展清单
- c++ - 如何使用模板继承和组件
- c - 这里有什么问题?我没有连接我的字符串?
- java - 使用 Spring RestTemplate 将图像和 PDF 作为 Base64 字符串返回
- image - 从 blob 读取二进制数据以显示 Image React Native
- segue - 对新的视图控制器执行 Segue - 准备 segue 快速失败 5
- datepicker - 如何将页脚日期选择器移到日期选择器之外?
- node.js - 如何使用 pkg 在 Node.js 程序中获取程序的当前目录?
- database - 为什么位置透明度称为位置透明度?
- c# - 如何在 Xamarin 中同步从 GraphQL 获取的数据和 SQLite?