forked from creationix/dukluv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp-echo.js
97 lines (91 loc) · 2.24 KB
/
tcp-echo.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
"use strict";
var p = require('./modules/utils.js').prettyPrint;
var Tcp = require('./modules/classes.js').Tcp;
var server, socket, client;
function Server(host, port) {
Tcp.call(this);
p("server", this);
this.bind(host, port);
this.listen(128, this.onConnection);
}
Server.prototype.__proto__ = Tcp.prototype;
Server.prototype.onConnection = function onConnection(err) {
assert(this === server);
if (err) { throw err; }
p("server.onconnection");
socket = new ClientHandler(this);
p("server.accept", socket);
this.accept(socket);
p("socket.readStart");
socket.readStart(socket.onRead);
};
function ClientHandler(server) {
Tcp.call(this);
p("socket", this);
this.server = server;
}
ClientHandler.prototype.__proto__ = Tcp.prototype;
ClientHandler.prototype.onRead = function onRead(err, data) {
assert(this === socket);
if (err) { throw err; }
p("socket.onread", data);
if (data) {
p("socket.write", data);
this.write(data);
}
else {
p("socket.shutdown");
this.shutdown();
p("socket.readStop");
this.readStop();
p("socket.close");
this.close();
p("server.close");
this.server.close();
}
};
function Client(host, port) {
Tcp.call(this);
p("client", this);
p("client.connect");
this.connect(host, port, this.onConnect);
}
Client.prototype.__proto__ = Tcp.prototype;
Client.prototype.onConnect = function onConnect(err) {
assert(this === client);
if (err) { throw err; }
this.readStart(this.onRead);
var buffer = Duktape.Buffer(3);
buffer[0] = 0x10;
buffer[1] = 0x00;
buffer[2] = 0x50;
p("client.write", buffer);
this.write(buffer);
p("client.write", "A \0 B");
this.write("A \0 B", this.onWrite);
};
Client.prototype.onRead = function onRead(err, data) {
assert(this === client);
if (err) { throw err; }
p("client.onread", data);
if (data) {
p("client.shutdown");
this.shutdown();
}
else {
p("client.close");
this.close();
}
};
Client.prototype.onWrite = function onWrite(err) {
assert(this === client);
if (err) { throw err; }
p("client.onwrite");
};
server = new Server("127.0.0.1", 1337);
client = new Client("127.0.0.1", 1337);
function assert(cond, message) {
if (!cond) {
throw new Error(message || "Assertion Failure");
}
}