UNPKG

1.98 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.TcpSocket = void 0;
4const constants_1 = require("../constants");
5const net_socket_closed_exception_1 = require("../errors/net-socket-closed.exception");
6const invalid_json_format_exception_1 = require("../errors/invalid-json-format.exception");
7class TcpSocket {
8 get netSocket() {
9 return this.socket;
10 }
11 constructor(socket) {
12 this.socket = socket;
13 this.isClosed = false;
14 this.socket.on(constants_1.DATA_EVENT, this.onData.bind(this));
15 this.socket.on(constants_1.CONNECT_EVENT, () => (this.isClosed = false));
16 this.socket.on(constants_1.CLOSE_EVENT, () => (this.isClosed = true));
17 this.socket.on(constants_1.ERROR_EVENT, () => (this.isClosed = true));
18 }
19 connect(port, host) {
20 this.socket.connect(port, host);
21 return this;
22 }
23 on(event, callback) {
24 this.socket.on(event, callback);
25 return this;
26 }
27 once(event, callback) {
28 this.socket.once(event, callback);
29 return this;
30 }
31 end() {
32 this.socket.end();
33 return this;
34 }
35 sendMessage(message, callback) {
36 if (this.isClosed) {
37 callback && callback(new net_socket_closed_exception_1.NetSocketClosedException());
38 return;
39 }
40 this.handleSend(message, callback);
41 }
42 onData(data) {
43 try {
44 this.handleData(data);
45 }
46 catch (e) {
47 this.socket.emit(constants_1.ERROR_EVENT, e.message);
48 this.socket.end();
49 }
50 }
51 emitMessage(data) {
52 let message;
53 try {
54 message = JSON.parse(data);
55 }
56 catch (e) {
57 throw new invalid_json_format_exception_1.InvalidJSONFormatException(e, data);
58 }
59 message = message || {};
60 this.socket.emit(constants_1.MESSAGE_EVENT, message);
61 }
62}
63exports.TcpSocket = TcpSocket;