Это моя первая практика после прочтения некоторых уроков и видео.По сути, мне нужно отправить сообщение с сервера (nodejs) клиенту (Angular 6).Сначала, когда клиентское приложение загружается, оно отправляет идентификатор пользователя на сервер для аутентификации.Затем сервер будет отправлять данные на основе этого пользователя.
Теперь моя проблема при первой загрузке и нескольких вызовах, соединение работает.Но затем при обновлении или около того, соединение разрывается.Мой клиент «утешает» консоль, но это никогда не удается.Это работает, только если я вручную перезагружаю сервер и перезагружаю клиент, чтобы можно было установить новое соединение.
Как я могу поддерживать довольно стабильное соединение в течение всего срока службы клиента?Время от времени readyState остается на 3 на сервере, то есть на соединении, с которым я путаюсь, потому что клиент пытается восстановить соединение ... просто не удается.
Мой сервер прост.index.js (Пытался поднять его на stackblitz, но не смог ... был бы признателен, если бы кто-нибудь смог выяснить файл зависимостей: сервер webjcket nodejs )
const express = require('express');
const bodyParser = require('body-parser');
const pg = require ('pg');
var ws = require('./ws')
var app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000, function () {
console.log('We are running on port 3000!')
})
ws.js:
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'error.log'})
]
});
var WebSocketServer = require("ws").Server,
wss = new WebSocketServer({
port: 40511
});
let data = {
'packet': ['amy1', 'amy2', 'amy3']
}
const mx = 2;
const mn = 0;
wss.on("connection", function(ws) {
ws.on("message", function(user) {
// client has called now. If the connection
// fails, the client does try to connection again and again -- no limit but it simply doesn't seem to have effect. When connecting, it simply sends user name
console.log("received: %s", user);
setInterval(function(){
var random = Math.floor(Math.random() * (mx - mn + 1) + mn);
if (ws.readyState == ws.OPEN){
ws.send(data['packet'][random]);
}
}, 3000);
});
});
Мой внешний интерфейс: service.ts
import { Observable} from 'rxjs';
export class WebSocketService {
socket: WebSocket;
constructor() { }
initConnection(): void {
if(!this.socket){
this.socket = new WebSocket('ws://localhost:40511');
// when connection is open, send user id
this.socket.onopen = () => this.socket.send(2);
}
}
manageState() : Observable<any>{
const vm = this;
return new Observable(observer => {
this.socket.onerror = (e) => {
// close it
this.socket.close();
observer.next('web socket communication closed due to error')
};
this.socket.onclose = (e) => {
//socket closed for any reason
setTimeout(function() {
console.log('try to connect')
vm.initConnection();
observer.next('still trying')
}, 1000);
}
});
}
onMessage(): Observable<any> {
// when message arrives:
return new Observable(observer => {
this.socket.onmessage = (e) => {
console.log(e.data);
observer.next(e.data)
};
});
}
}
component.ts:
// initialize the connection
this.service.initConnection();
this.service.onMessage().subscribe(
data => {
// we have got data
console.log('data came ', data)
},
err => {
console.log("error websocking service ", err);
}
);
// track state of the communication, letting the service to reconnect if connection is dropped
this.service.manageState().subscribe(data => {
console.log(data);
});