我们可以使用Angular 6客户端套接字连接到Erlang套接字服务器吗?

时间:2019-01-09 13:02:42

标签: socket.io erlang angular6

我正在尝试使用Socket.io-client中的Angular 6客户端连接到基于Erlang的服务器。我可以与服务器建立连接,但是在将数据发送到服务器后,无法从服务器获得任何类型的响应。

我在下面附上我的代码段。

// websocket.service.ts

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
import * as io from 'socket.io-client';
import * as Rx from 'rxjs/Rx';
import { LocationInfo } from '../core/locationInfo.model';
import { Event } from '../core/event.enum';

@Injectable({
providedIn: 'root'
})

export class WebsocketService {

private socket:SocketIOClient.Socket;

constructor() {}

connect(): Rx.Subject<MessageEvent> {
this.socket = io.connect('localhost:3000');
// We define our observable which will observe any incoming messages
// from our socket.io server.
let observable = new Observable(observer => {
  console.log('Observable created')
    this.socket.on('connect', (data) => {
      console.log(data)
    })

    this.socket.on('message', (data) => {
      console.log("Received message from Websocket Server"+data)
      observer.next(data);
    })
    return () => {
      this.socket.disconnect();
    }
});

// We define our Observer which will listen to messages
// from our other components and send messages back to our
// socket server whenever the `next()` method is called.
let observer = {
    next: (data: Object) => {
        console.log(JSON.stringify(data))
        this.socket.emit('join',JSON.stringify('Hiiii'));
        this.socket.send(JSON.stringify('Hiiii'))
    },
};

// we return our Rx.Subject which is a combination
// of both an observer and observable.
return Rx.Subject.create(observer, observable);
}
}

// app.component.ts

constructor(private liveLocServ: getLocationService) 
{}
ngOnInit() {
 this.liveLocServ.messages.subscribe(msg => {
  console.log(msg);
 })
}

// getLocation.service.ts

 import { Injectable } from '@angular/core';
 import { WebsocketService } from './websocket.service';
 import { Subject } from 'rxjs/Rx';
 import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class getLocationService {

messages: Subject<any>;

// Our constructor calls our wsService connect method
constructor(private wsService: WebsocketService) {
this.messages = <Subject<any>>wsService
  .connect()
  .pipe(map((response: any): any => {
    return response;
  }))
}

// Our simplified interface for sending
// messages back to our socket.io server
sendMsg(input) {
 this.messages.next(input);
}

}

1 个答案:

答案 0 :(得分:0)

我找到了在angular 6中使用websocket客户端与erlang服务器连接的解决方案,因此在erlang服务器上应该实现了websocket服务器。