使用WebSocket从服务器获取响应

时间:2019-02-19 15:31:55

标签: angular websocket server socket.io client

使用WebSocket获取响应grom服务器

嗨,

因此,基本上,我需要验证用户输入的数据是否在我的数据库中。 为了在客户端和服务器之间建立通信,我使用了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)。此功能使用以下服务,该服务使用将数据发送到服务器的WebSocket。

  

send-difference.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);
  }

}

最后,我只想澄清一下我对所有后端用户都是新手,因此,如果我的问题有点愚蠢或她没有道理,请随时向我解释一下我的想法关于websockets缺少(或向我提出解决方案)。我也听说过socket.io,但是我想知道websockets是否是更好的选择。

谢谢。

0 个答案:

没有答案