| 1 |
/* |
| 2 |
* Copyright (C)2005-2018 Haxe Foundation |
| 3 |
* |
| 4 |
* Permission is hereby granted, free of charge, to any person obtaining a |
| 5 |
* copy of this software and associated documentation files (the "Software"), |
| 6 |
* to deal in the Software without restriction, including without limitation |
| 7 |
* the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 8 |
* and/or sell copies of the Software, and to permit persons to whom the |
| 9 |
* Software is furnished to do so, subject to the following conditions: |
| 10 |
* |
| 11 |
* The above copyright notice and this permission notice shall be included in |
| 12 |
* all copies or substantial portions of the Software. |
| 13 |
* |
| 14 |
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 |
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 |
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 |
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 |
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 19 |
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 20 |
* DEALINGS IN THE SOFTWARE. |
| 21 |
*/ |
| 22 |
package neko.net; |
| 23 |
|
| 24 |
private typedef ThreadInfos = { |
| 25 |
var id : Int; |
| 26 |
var t : neko.vm.Thread; |
| 27 |
var p : neko.net.Poll; |
| 28 |
var socks : Array<sys.net.Socket>; |
| 29 |
} |
| 30 |
|
| 31 |
private typedef ClientInfos<Client> = { |
| 32 |
var client : Client; |
| 33 |
var sock : sys.net.Socket; |
| 34 |
var thread : ThreadInfos; |
| 35 |
var buf : haxe.io.Bytes; |
| 36 |
var bufpos : Int; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
The ThreadServer can be used to easily create a multithreaded server where each thread polls multiple connections. |
| 41 |
To use it, at a minimum you must override or rebind clientConnected, readClientMessage, and clientMessage and you must define your Client and Message. |
| 42 |
**/ |
| 43 |
class ThreadServer<Client,Message> { |
| 44 |
|
| 45 |
var threads : Array<ThreadInfos>; |
| 46 |
var sock : sys.net.Socket; |
| 47 |
var worker : neko.vm.Thread; |
| 48 |
var timer : neko.vm.Thread; |
| 49 |
|
| 50 |
/** |
| 51 |
Number of total connections the server will accept. |
| 52 |
**/ |
| 53 |
public var listen : Int; |
| 54 |
|
| 55 |
/** |
| 56 |
Number of server threads. |
| 57 |
**/ |
| 58 |
public var nthreads : Int; |
| 59 |
|
| 60 |
/** |
| 61 |
Polling timeout. |
| 62 |
**/ |
| 63 |
public var connectLag : Float; |
| 64 |
|
| 65 |
/** |
| 66 |
Stream to send error messages. |
| 67 |
**/ |
| 68 |
public var errorOutput : haxe.io.Output; |
| 69 |
|
| 70 |
/** |
| 71 |
Space allocated to buffers when they are created. |
| 72 |
**/ |
| 73 |
public var initialBufferSize : Int; |
| 74 |
|
| 75 |
/** |
| 76 |
Maximum size of buffered data read from a socket. An exception is thrown if the buffer exceeds this value. |
| 77 |
**/ |
| 78 |
public var maxBufferSize : Int; |
| 79 |
|
| 80 |
/** |
| 81 |
Minimum message size. |
| 82 |
**/ |
| 83 |
public var messageHeaderSize : Int; |
| 84 |
|
| 85 |
/** |
| 86 |
Time between calls to update. |
| 87 |
**/ |
| 88 |
public var updateTime : Float; |
| 89 |
|
| 90 |
/** |
| 91 |
The most sockets a thread will handle. |
| 92 |
**/ |
| 93 |
public var maxSockPerThread : Int; |
| 94 |
|
| 95 |
/** |
| 96 |
Creates a ThreadServer. |
| 97 |
**/ |
| 98 |
public function new() { |
| 99 |
threads = new Array(); |
| 100 |
nthreads = if( Sys.systemName() == "Windows" ) 150 else 10; |
| 101 |
messageHeaderSize = 1; |
| 102 |
listen = 10; |
| 103 |
connectLag = 0.5; |
| 104 |
errorOutput = Sys.stderr(); |
| 105 |
initialBufferSize = (1 << 10); |
| 106 |
maxBufferSize = (1 << 16); |
| 107 |
maxSockPerThread = 64; |
| 108 |
updateTime = 1; |
| 109 |
} |
| 110 |
|
| 111 |
function runThread(t) { |
| 112 |
while( true ) { |
| 113 |
try { |
| 114 |
loopThread(t); |
| 115 |
} catch( e : Dynamic ) { |
| 116 |
logError(e); |
| 117 |
} |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
function readClientData( c : ClientInfos<Client> ) { |
| 122 |
var available = c.buf.length - c.bufpos; |
| 123 |
if( available == 0 ) { |
| 124 |
var newsize = c.buf.length * 2; |
| 125 |
if( newsize > maxBufferSize ) { |
| 126 |
newsize = maxBufferSize; |
| 127 |
if( c.buf.length == maxBufferSize ) |
| 128 |
throw "Max buffer size reached"; |
| 129 |
} |
| 130 |
var newbuf = haxe.io.Bytes.alloc(newsize); |
| 131 |
newbuf.blit(0,c.buf,0,c.bufpos); |
| 132 |
c.buf = newbuf; |
| 133 |
available = newsize - c.bufpos; |
| 134 |
} |
| 135 |
var bytes = c.sock.input.readBytes(c.buf,c.bufpos,available); |
| 136 |
var pos = 0; |
| 137 |
var len = c.bufpos + bytes; |
| 138 |
while( len >= messageHeaderSize ) { |
| 139 |
var m = readClientMessage(c.client,c.buf,pos,len); |
| 140 |
if( m == null ) |
| 141 |
break; |
| 142 |
pos += m.bytes; |
| 143 |
len -= m.bytes; |
| 144 |
work(clientMessage.bind(c.client,m.msg)); |
| 145 |
} |
| 146 |
if( pos > 0 ) |
| 147 |
c.buf.blit(0,c.buf,pos,len); |
| 148 |
c.bufpos = len; |
| 149 |
} |
| 150 |
|
| 151 |
function loopThread( t : ThreadInfos ) { |
| 152 |
if( t.socks.length > 0 ) |
| 153 |
for( s in t.p.poll(t.socks,connectLag) ) { |
| 154 |
var infos : ClientInfos<Client> = s.custom; |
| 155 |
try { |
| 156 |
readClientData(infos); |
| 157 |
} catch( e : Dynamic ) { |
| 158 |
t.socks.remove(s); |
| 159 |
if( !Std.is(e,haxe.io.Eof) && !Std.is(e,haxe.io.Error) ) |
| 160 |
logError(e); |
| 161 |
work(doClientDisconnected.bind(s,infos.client)); |
| 162 |
} |
| 163 |
} |
| 164 |
while( true ) { |
| 165 |
var m : { s : sys.net.Socket, cnx : Bool } = neko.vm.Thread.readMessage(t.socks.length == 0); |
| 166 |
if( m == null ) |
| 167 |
break; |
| 168 |
if( m.cnx ) |
| 169 |
t.socks.push(m.s); |
| 170 |
else if( t.socks.remove(m.s) ) { |
| 171 |
var infos : ClientInfos<Client> = m.s.custom; |
| 172 |
work(doClientDisconnected.bind(m.s,infos.client)); |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
function doClientDisconnected(s:sys.net.Socket,c) { |
| 178 |
try s.close() catch( e : Dynamic ) {}; |
| 179 |
clientDisconnected(c); |
| 180 |
} |
| 181 |
|
| 182 |
function runWorker() { |
| 183 |
while( true ) { |
| 184 |
var f = neko.vm.Thread.readMessage(true); |
| 185 |
try { |
| 186 |
f(); |
| 187 |
} catch( e : Dynamic ) { |
| 188 |
logError(e); |
| 189 |
} |
| 190 |
try { |
| 191 |
afterEvent(); |
| 192 |
} catch( e : Dynamic ) { |
| 193 |
logError(e); |
| 194 |
} |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
/** |
| 199 |
Internally used to delegate something to the worker thread. |
| 200 |
**/ |
| 201 |
public function work( f : Void -> Void ) { |
| 202 |
worker.sendMessage(f); |
| 203 |
} |
| 204 |
|
| 205 |
function logError( e : Dynamic ) { |
| 206 |
var stack = haxe.CallStack.exceptionStack(); |
| 207 |
if( neko.vm.Thread.current() == worker ) |
| 208 |
onError(e,stack); |
| 209 |
else |
| 210 |
work(onError.bind(e,stack)); |
| 211 |
} |
| 212 |
|
| 213 |
function addClient( sock : sys.net.Socket ) { |
| 214 |
var start = Std.random(nthreads); |
| 215 |
for( i in 0...nthreads ) { |
| 216 |
var t = threads[(start + i)%nthreads]; |
| 217 |
if( t.socks.length < maxSockPerThread ) { |
| 218 |
var infos : ClientInfos<Client> = { |
| 219 |
thread : t, |
| 220 |
client : clientConnected(sock), |
| 221 |
sock : sock, |
| 222 |
buf : haxe.io.Bytes.alloc(initialBufferSize), |
| 223 |
bufpos : 0, |
| 224 |
}; |
| 225 |
sock.custom = infos; |
| 226 |
infos.thread.t.sendMessage({ s : sock, cnx : true }); |
| 227 |
return; |
| 228 |
} |
| 229 |
} |
| 230 |
refuseClient(sock); |
| 231 |
} |
| 232 |
|
| 233 |
function refuseClient( sock : sys.net.Socket) { |
| 234 |
// we have reached maximum number of active clients |
| 235 |
sock.close(); |
| 236 |
} |
| 237 |
|
| 238 |
function runTimer() { |
| 239 |
var l = new neko.vm.Lock(); |
| 240 |
while( true ) { |
| 241 |
l.wait(updateTime); |
| 242 |
work(update); |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
function init() { |
| 247 |
worker = neko.vm.Thread.create(runWorker); |
| 248 |
timer = neko.vm.Thread.create(runTimer); |
| 249 |
for( i in 0...nthreads ) { |
| 250 |
var t = { |
| 251 |
id : i, |
| 252 |
t : null, |
| 253 |
socks : new Array(), |
| 254 |
p : new neko.net.Poll(maxSockPerThread), |
| 255 |
}; |
| 256 |
threads.push(t); |
| 257 |
t.t = neko.vm.Thread.create(runThread.bind(t)); |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
/** |
| 262 |
Called when the server gets a new connection. |
| 263 |
**/ |
| 264 |
public function addSocket( s : sys.net.Socket ) { |
| 265 |
s.setBlocking(false); |
| 266 |
work(addClient.bind(s)); |
| 267 |
} |
| 268 |
|
| 269 |
/** |
| 270 |
Start the server at the specified host and port. |
| 271 |
**/ |
| 272 |
public function run( host, port ) { |
| 273 |
sock = new sys.net.Socket(); |
| 274 |
sock.bind(new sys.net.Host(host),port); |
| 275 |
sock.listen(listen); |
| 276 |
init(); |
| 277 |
while( true ) { |
| 278 |
try { |
| 279 |
addSocket(sock.accept()); |
| 280 |
} catch( e : Dynamic ) { |
| 281 |
logError(e); |
| 282 |
} |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
/** |
| 287 |
Sends data to a client. |
| 288 |
**/ |
| 289 |
public function sendData( s : sys.net.Socket, data : String ) { |
| 290 |
try { |
| 291 |
s.write(data); |
| 292 |
} catch( e : Dynamic ) { |
| 293 |
stopClient(s); |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
/** |
| 298 |
Shutdown a client's connection and remove them from the server. |
| 299 |
**/ |
| 300 |
public function stopClient( s : sys.net.Socket ) { |
| 301 |
var infos : ClientInfos<Client> = s.custom; |
| 302 |
try s.shutdown(true,true) catch( e : Dynamic ) { }; |
| 303 |
infos.thread.t.sendMessage({ s : s, cnx : false }); |
| 304 |
} |
| 305 |
|
| 306 |
// --- CUSTOMIZABLE API --- |
| 307 |
|
| 308 |
/** |
| 309 |
Called when an error has occurred. |
| 310 |
**/ |
| 311 |
public dynamic function onError( e : Dynamic, stack ) { |
| 312 |
var estr = try Std.string(e) catch( e2 : Dynamic ) "???" + try "["+Std.string(e2)+"]" catch( e : Dynamic ) ""; |
| 313 |
errorOutput.writeString( estr + "\n" + haxe.CallStack.toString(stack) ); |
| 314 |
errorOutput.flush(); |
| 315 |
} |
| 316 |
|
| 317 |
/** |
| 318 |
Called when a client connects. Returns a client object. |
| 319 |
**/ |
| 320 |
public dynamic function clientConnected( s : sys.net.Socket ) : Client { |
| 321 |
return null; |
| 322 |
} |
| 323 |
|
| 324 |
/** |
| 325 |
Called when a client disconnects or an error forces the connection to close. |
| 326 |
**/ |
| 327 |
public dynamic function clientDisconnected( c : Client ) { |
| 328 |
} |
| 329 |
|
| 330 |
/** |
| 331 |
Called when data has been read from a socket. This method should try to extract a message from the buffer. |
| 332 |
The available data resides in buf, starts at pos, and is len bytes wide. Return the new message and the number of bytes read from the buffer. |
| 333 |
If no message could be read, return null. |
| 334 |
**/ |
| 335 |
public dynamic function readClientMessage( c : Client, buf : haxe.io.Bytes, pos : Int, len : Int ) : { msg : Message, bytes : Int } { |
| 336 |
return { |
| 337 |
msg : null, |
| 338 |
bytes : len, |
| 339 |
}; |
| 340 |
} |
| 341 |
|
| 342 |
/** |
| 343 |
Called when a message has been received. Message handling code should go here. |
| 344 |
**/ |
| 345 |
public dynamic function clientMessage( c : Client, msg : Message ) { |
| 346 |
} |
| 347 |
|
| 348 |
/** |
| 349 |
This method is called periodically. It can be used to do server maintenance. |
| 350 |
**/ |
| 351 |
public dynamic function update() { |
| 352 |
} |
| 353 |
|
| 354 |
/** |
| 355 |
Called after a client connects, disconnects, a message is received, or an update is performed. |
| 356 |
**/ |
| 357 |
public dynamic function afterEvent() { |
| 358 |
} |
| 359 |
|
| 360 |
} |