/
websocket.service.ts
66 lines (53 loc) · 1.84 KB
/
websocket.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { EventUserDto } from './../Interfaces/EventUserDto';
import { EventDto } from './../Interfaces/EventDto';
import { World } from '../Interfaces/World';
import { WorldService } from './world.service';
import { EventService } from 'app/services/event.service';
import { UserService } from 'app/services/user.service';
import { Message } from '../Interfaces/Message';
import { Event } from '../Interfaces/Event';
import * as SockJS from 'sockjs-client';
import { Injectable } from '@angular/core';
import { Stomp } from '@stomp/stompjs';
import { User } from 'app/Interfaces/User';
@Injectable()
export class WebsocketService {
private serverUrl = 'http://localhost:8080/socket';
private stompClient;
private user: User;
private currentWorld: World;
private chatStomp = null;
constructor
( public userService: UserService,
public eventService: EventService,
public worldService: WorldService
) {
userService.user$.subscribe(user => { this.user = user });
worldService.currentWorld$.subscribe(currentWorld => { this.currentWorld = currentWorld });
this.initializeWebSocketConnection();
}
initializeWebSocketConnection() {
this.closeWebSocket();
const ws = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(ws);
const that = this;
this.stompClient.connect({}, function(frame) {
this.chatStomp = that.stompClient.subscribe('/chat', message => {
const eventUserDto: EventUserDto = JSON.parse(message.body);
that.eventService.addEvent(eventUserDto);
});
});
}
sendMessage(message) {
const messageDto: Message = {
message: message,
userId: this.user.id
};
this.stompClient.send('/app/send/message' , {}, JSON.stringify(messageDto));
}
closeWebSocket() {
if (this.stompClient) {
this.stompClient.disconnect();
}
}
}