无法读取angular上的websocket [英] Can't read websocket on angular
问题描述
我正在尝试通过Angular 8应用程序和简单服务器之间的websockets交换信息.奇怪的是,我能够将信息发送到服务器,但是我似乎找不到如何连接应用程序以接收回声的消息.
I am trying to exchange info through websockets between an Angular 8 app and a simple server. Strangely I'm able to send info to the server, but I can't seem to find how to wire the app to receive back my echoes.
这是应用程序组件:
import { Component } from '@angular/core';
import { webSocket, WebSocketSubject } from "rxjs/webSocket";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
ws : WebSocketSubject<any>;
ngOnInit() {}
constructor() {
this.ws = webSocket('ws://localhost:8999');
this.ws.subscribe({
next : (data) => console.log(`Received ${data}`),
error : (err) => {},
complete : () => {}
});
}
buttonClick() {
this.ws.next("test");
}
}
这是服务器:
import * as express from 'express';
import * as http from 'http';
import * as WebSocket from 'ws';
const server = http.createServer(express());
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws: WebSocket) => {
// Print and echo
ws.on('message', (data) => {
console.log(`received: ${data}`);
ws.send(`echo: ${data}`);
})
});
setInterval(() => wss.clients.forEach(ws => ws.send(`ping!`)), 2000);
// Start server
server.listen(process.env.PORT || 8999, () => {
console.log(`Server started on port ${(<WebSocket.AddressInfo>server.address()).port}`);
});
用一个简单的工具测试服务器至少可以确认我这一面正在工作
And testing the server with a simple tool at least confirms me that side is working
推荐答案
您没有得到任何错误,因为您使用空的error
回调跳过了所有错误:
You don't get any errors because you skip all the errors by using empty error
callback:
this.ws.subscribe({
next : (data) => console.log(`Received ${data}`),
error : console.log, <==================================== add this
complete : () => {}
});
记录错误后,您应该会得到类似以下内容的信息:
Once you log the errors you should get something like:
SyntaxError:JSON中位置0处的意外令牌p 在JSON.parse()
SyntaxError: Unexpected token p in JSON at position 0 at JSON.parse ()
这似乎来自您的websocket的响应未正确处理.这是因为rxjs需要json,但是您正在发送纯字符串. rxjs的Websocket实现使用默认配置,如下所示:
This seems that the response from your websocket wasn't handled properly. That's because rxjs expects json but you're sending plain string. Websocket implementation from rxjs uses default configuration as follows:
const DEFAULT_WEBSOCKET_CONFIG: WebSocketSubjectConfig<any> = {
url: '',
deserializer: (e: MessageEvent) => JSON.parse(e.data),
serializer: (value: any) => JSON.stringify(value),
};
应该如何解决?
您可以从服务器发送json或提供自定义deserializer
:
You can either send json from server or provide custom deserializer
:
this.ws = webSocket({
url: 'ws://localhost:8999',
deserializer: e => e.data
});
这篇关于无法读取angular上的websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!