问题
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.
Here's the app component :
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");
}
}
Here's the server :
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
回答1:
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: Unexpected token p in JSON at position 0 at JSON.parse ()
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),
};
How should it be fixed?
You can either send json from server or provide custom deserializer
:
this.ws = webSocket({
url: 'ws://localhost:8999',
deserializer: e => e.data
});
来源:https://stackoverflow.com/questions/58926375/cant-read-websocket-on-angular