This repository has been archived by the owner on May 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
pysocket.js
99 lines (86 loc) · 1.99 KB
/
pysocket.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use babel';
var Socket = require('net').Socket;
export default class PySocket {
constructor(address,params){
this.type = "socket"
this.stream = new Socket();
this.stream.setTimeout(params.timeout)
this.connected = false
this.params = params
this.address = address
this.receive_buffer = ""
this.on_error_called = false
}
connect(onconnect,onerror,ontimeout){
this.onconnect = onconnect
this.onerror = onerror
this.ontimeout = ontimeout
this.username_sent = false
this.password_sent = false
var _this = this
this.stream.connect(this.params.port,this.address);
this.stream.on('connect', function () {
onconnect()
});
this.stream.on('timeout', function () {
ontimeout()
});
this.stream.on('error', function (error) {
if(!_this.on_error_called){
_this.on_error_called = true
onerror(error)
}
});
this.stream.on('close', function (had_error) {
if(had_error && !_this.on_error_called){
_this.on_error_called = true
onerror()
}
});
this.stream.on('end', function () {
if(!_this.on_error_called){
_this.on_error_called = true
}
});
}
disconnect(cb){
if(this.stream){
this.stream.destroy();
this.stream = null;
}
cb()
}
registerListener(cb){
this.onmessage = cb
this.stream.on('data', function (data) {
var raw = Buffer(data)
cb(data,raw)
});
}
send(mssg,cb){
mssg = mssg.replace('\x1b', '\x1b\x1b')
var data = new Buffer(mssg,"binary")
this.send_raw(data,cb)
}
send_raw(data,cb){
if(this.stream){
this.stream.write(data,function(){
if(cb) cb();
})
}else{
cb(new Error("Not connected"))
}
}
send_cmd(cmd,cb){
var mssg = '\x1b\x1b' + cmd
var data = new Buffer(mssg,"binary")
this.send_raw(data,cb)
}
sendPing(cb){
if(cb) cb(null)
return true
}
flush(cb){
cb()
}
}