Получение сервера отклика с помощью WebSocket
Привет,
Итак, в основном мне нужно проверить, находятся ли введенные пользователем данные в моей БД.Чтобы установить связь между моим клиентом и сервером, я использовал Websocket.Проблема в том, что я не совсем уверен, как обращаться с серверной стороной.Я хотел бы знать, как получить данные от пользователя и повторно отправить ему ответ, который сообщает, действительны ли введенные им данные.
Вот что у меня есть на данный момент:
game-view.component.ts
import { Component, OnInit } from '@angular/core';
import { SendDifferencesService } from '../services/send-differences.service';
@Component({
selector: 'app-game-view',
templateUrl: './game-view.component.html',
styleUrls: ['./game-view.component.scss'],
providers: [ SendDifferencesService ]
})
export class GameViewComponent implements OnInit {
private seconds: number = 0;
private minutes: number = 0;
//private differences: number = 0;
private interval: NodeJS.Timer;
private Point2D = {
coordinateX: 0,
coordinateY: 0,
}
constructor(private differenceService: SendDifferencesService) { }
ngOnInit() {
this.startTimer();
}
public startTimer() {
this.interval = setInterval(() => {
if(this.seconds < 60) {
this.seconds++;
} else {
this.seconds = 0;
this.minutes++;
}
},1000)
}
public EndTimer() {
clearInterval(this.interval);
}
public getSeconds(){
return this.seconds;
}
public getMinutes(){
return this.minutes;
}
public submitDifference(event:MouseEvent){
if(event.offsetX != null && event.offsetY!= null)
{
this.Point2D.coordinateX = event.offsetX;
this.Point2D.coordinateY = event.offsetY;
alert(this.Point2D.coordinateX + ":" + this.Point2D.coordinateY );
this.differenceService.coordinates.next(this.Point2D);
}
}
}
В этом файле вам нужно рассмотреть только последнюю функцию (submitDifference).Эта функция использует следующий сервис, который использует WebSockets, которые отправляют данные на сервер.
send-diff.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { WebsocketService } from './websocket.service';
export interface Point2D {
coordinateX: number,
coordinateY: number
}
const DIFFERENCE_URL= 'ws://localhost:3000/api/difference';
@Injectable()
export class SendDifferencesService {
public coordinates: Subject<Point2D>;
constructor(wsService: WebsocketService) {
this.coordinates = <Subject<Point2D>>wsService
.connect(DIFFERENCE_URL).pipe(
map((response: MessageEvent): Point2D => {
let data = JSON.parse(response.data);
return {
coordinateX: data.coordinateX,
coordinateY: data.coordinateY
}
}));
}
}
И вот мой websocket(все эти файлы находятся на стороне клиента):
import { Injectable } from '@angular/core';
import * as Rx from 'rxjs';
@Injectable()
export class WebsocketService {
constructor() { }
private subject: Rx.Subject<MessageEvent>;
public connect(url:string): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
console.log("Successfully connected: " + url);
}
return this.subject;
}
private create(url:string): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);
let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
})
let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
}
return Rx.Subject.create(observer, observable);
}
}
Последнее, я просто хочу уточнить, что я новичок во всей серверной части, так что если это мой вопрос чувствует себя немногоглупо или что она не имеет смысла, не стесняйтесь объяснять мне, что мне не хватает в веб-розетках (или предлагать мне решение).Я также слышал о socket.io, но я хочу знать, являются ли веб-сокеты лучшим выбором.
Спасибо.