This repository has been archived by the owner on Mar 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkStream.hx
71 lines (47 loc) · 2.46 KB
/
NetworkStream.hx
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
package rn.net;
import haxe.io.*;
class NetworkStream {
var inputBufferSize:Int;
var inputBuffer:BufferInput;
var outputStream:Output;
//----------------------------------------------------------------------------------------------
public var canRead (get, null) : Bool;
function get_canRead () return if (inputBufferSize > 0 && inputBuffer != null) try { refill(); true; } catch (e:Dynamic) { Type.getClass(e) != haxe.io.Eof; } else false;
public var canWrite (get, null) : Bool;
function get_canWrite () return outputStream != null;
//----------------------------------------------------------------------------------------------
public var length (get, null) : Int;
function get_length () return canRead ? inputBuffer.available : 0;
public var dataAvailable (get, null) : Bool;
function get_dataAvailable () return length > 0;
//----------------------------------------------------------------------------------------------
public function new (?inputBufferSize:Int) {
this.inputBufferSize = inputBufferSize == null ? 1 : inputBufferSize;
inputBuffer = null;
}
//----------------------------------------------------------------------------------------------
public function setStream (inputStream:Input, outputStream:Output) {
inputBuffer = new BufferInput(inputStream, Bytes.alloc(inputBufferSize));
this.outputStream = outputStream;
}
public function setSocketStream (socket:sys.net.Socket) setStream(socket.input, socket.output);
//----------------------------------------------------------------------------------------------
public function refill (force:Bool = false)
if (inputBuffer.available < 1 || force) inputBuffer.refill();
public function readByte ()
return dataAvailable ? try { inputBuffer.readByte(); } catch (e:Dynamic) { -1; } : -1;
public function writeByte (data:Int)
return if (canWrite && data != null) try { outputStream.writeByte(data); true; } catch (e:Dynamic) { false; } else false;
public function write (data:Bytes)
return if (canWrite && (data != null ? data.length > 0 : false)) try { outputStream.write(data); true; } catch (e:Dynamic) { false; } else false;
//----------------------------------------------------------------------------------------------
public function close () {
inputBufferSize = 0;
if (inputBuffer != null)
try { inputBuffer.close(); } catch (e:Dynamic) { }
inputBuffer = null;
if (outputStream != null)
try { outputStream.close(); } catch (e:Dynamic) { }
outputStream = null;
}
}