-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocketbase.ts
More file actions
298 lines (233 loc) · 7.73 KB
/
socketbase.ts
File metadata and controls
298 lines (233 loc) · 7.73 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import {Buffer} from 'buffer';
import net = require('net');
import dgram = require('dgram');
import Event = require('events');
import {Session} from './lib/session';
import {Mailbox} from './lib/mailbox';
import {NetEngine,TcpEngine,UdpEngine} from './lib/net-engine';
import { setTimeout } from 'timers';
enum NetProto{
TCP=1,
UDP
}
interface SocketBase{
// send(sid:string,data:any,cb?);
}
interface RpcMsg{
toBuf():Buffer;
fromBuf(data:Buffer ):RpcMsg;
id():string;
}
class Amsg implements RpcMsg{
toBuf(){
return Buffer.from("abcd");
}
fromBuf( data:Buffer){
return this;
}
id():string{
return "";
}
}
class Router implements SocketBase{
private _server:net.Server|dgram.Socket;
private _netProto:NetProto;
private _host:string;
private _port:number;
private _sessions:Map<string,Session>;
private _serialId:number;
private _packetHandler:(data:Array<Buffer>)=>void;
constructor(type:NetProto,host:string,port:number,packetHandler:(data:Array<Buffer>)=>void ){
this._netProto = type;
this._host = host;
this._port = port;
this._serialId =0 ;
this._sessions = new Map<string,Session>();
this._packetHandler = packetHandler;
}
send(sid:string,data:Buffer,cb){
let session = this._sessions[sid];
if( !session ){
console.error(`session ${sid} not found.`)
return false;
}
return session.send(data,cb );
}
recv(data:Array<Buffer>,session:Session){
}
bind(){
let self=this;
if( self._netProto == NetProto.TCP ){
self._server = new net.Server( (socket)=>{
self._serialId++;
let netEngine = new TcpEngine(socket);
let session = new Session(this);
let mailbox = new Mailbox(session,netEngine,10,10 );
session.setMailBox(mailbox);
//self._sessions[self._serialId]= session;
self._sessions[socket.remoteAddress] = session;
console.log('connect addr:',socket.remoteAddress);
})
self._server.listen(self._port);
self._server.on('error',(err)=>{
console.error('server error!',err);
})
}else if(self._netProto == NetProto.UDP ){
self._server = dgram.createSocket('udp4');
self._server.on('message',(msg,info)=>{
let session = self._sessions[info.address]
if( !!session ){
//recv
session.netEngine.decode(msg);
}else{
session = new Session(this);
let netEngine = new UdpEngine();
let mailbox = new Mailbox(session,netEngine,10,10);
self._sessions[info.address] =session;
}
});
}else{
// to do
console.error(`error type:${self._netProto}`);
}
}
}
enum NetStatus{
Connected=1,
Closed,
Connecting
}
class RpcCB{
private _decode:(data:Buffer)=>RpcMsg;
private _cb:(error:Error,msg:RpcMsg)=>void;
constructor(decode:( data:Buffer) =>RpcMsg, cb:(error:Error,msg:RpcMsg)=>void){
this._decode = decode;
this._cb = cb;
}
}
class Dealer implements SocketBase{
private _socket:net.Socket|dgram.Socket;
private _netProto:NetProto;
private _host:string;
private _port:number;
private _session:Session;
private _serialId:number;
private _status:NetStatus;
private _connected:boolean;
private _rpcId:number;
private _packetHandler:(data:Array<Buffer>)=>void;
// private _cbs:Map<number,(err:Error,reply:RpcMsg)=>void >;
private _cbs:Map<number,RpcCB>;
private _cbsTimer:Map<number,NodeJS.Timer>;
constructor(type:NetProto,host:string,port:number,packetHandler:(data:Array<Buffer>)=>void){
this._netProto = type;
this._host = host;
this._port = port;
this._serialId =0 ;
this._status = NetStatus.Closed;
this._connected= false;
this._packetHandler = packetHandler;
this._rpcId=0;
// this._cbs = new Map<number, (err:Error,reply:RpcMsg)=>void>();
this._cbs = new Map<number,RpcCB>();
this._cbsTimer = new Map<number, NodeJS.Timer>();
}
notify(msg:RpcMsg){
let rpcId = this._rpcId;
let header={
rpcId:rpcId,
serviceId:msg.id()
}
this.send( [ Buffer.from( JSON.stringify(header) ), msg.toBuf() ] )
}
req1(msg:RpcMsg,cb:(err:Error,reply:RpcMsg)=>void){
let rpcId = this._rpcId;
let header={
rpcId:rpcId,
serviceId:msg.id()
}
this.send( [ Buffer.from( JSON.stringify(header) ), msg.toBuf() ] );
this._cbs[rpcId] = cb;
this._cbsTimer[ rpcId ] = setTimeout(()=>{
//
this._cbsTimer[rpcId] = null;
if( !!this._cbs[rpcId] ){
this._cbs[rpcId].cb( new Error("time out"),null );
this._cbs[rpcId] = null;
}
},10000),
this._rpcId++;
}
req(msg: RpcMsg) {
return new Promise((resolve) => {
let rpcId = this._rpcId;
let header = {
rpcId: rpcId,
serviceId: msg.id()
}
this.send([Buffer.from(JSON.stringify(header)), msg.toBuf()]);
this._cbs[rpcId] = resolve;
this._cbsTimer[rpcId] = setTimeout(() => {
//
this._cbsTimer[rpcId] = null;
if (!!this._cbs[rpcId]) {
this._cbs[rpcId].cb(new Error("time out"), null);
this._cbs[rpcId] = null;
}
}, 10000),
this._rpcId++;
})
}
recv(data:Array<Buffer>){
// to do ,head include error.
let header = JSON.parse( data[0].toString('utf8') );
let rpc= this._cbs[header.rpcId];
if( !!rpc){
//to pro
if( !!header.error ){
rpc.cb(new Error(header.error),null );
}else{
let body = data[1];
rpc.cb(null, rpc.decode(body) );
}
}
}
bind():boolean{
let self =this;
if( this._netProto == NetProto.TCP ){
self._status = NetStatus.Connecting;
this._session = new Session( this);
let mailbox = new Mailbox(this._session,null,10,10);
let socket = net.connect(this._port,this._host,()=>{
self._connected = true;
self._status = NetStatus.Connected;
let netEngine = new TcpEngine(socket);
mailbox.netEngine = netEngine;
})
this._session.on('close',()=>{
//reconnect?
});
return true;
}else if(this._netProto == NetProto.UDP ){
//notice .. server always use tcp.
this._socket = dgram.createSocket('udp4');
this._status = NetStatus.Connected;
this._session = new Session(this);
let netEngine = new UdpEngine();
let mailbox = new Mailbox(this._session,netEngine,10,10);
return true;
}else{
console.error(`can not create such type ${this._netProto}`);
return false;
}
}
send(data:Array<Buffer>):boolean{
if( !this._session ){
if( !this.bind() ){
return false;
}
}
return this._session.send(data);
}
}
export {Router,Dealer,NetProto};