This commit is contained in:
2014-06-23 10:10:31 +04:00
parent 44c82ec71c
commit 11d4b1762d
7 changed files with 129 additions and 41 deletions

View File

@@ -0,0 +1,88 @@
package ru.m.armageddon.core.connect;
import haxe.io.BytesOutput;
import protohx.Message;
import haxe.io.Bytes;
import flash.events.ErrorEvent;
import flash.events.ProgressEvent;
import flash.events.Event;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent;
import flash.net.Socket;
class FlashConnection implements IConnection {
private static var MAP:Map<Int, Map<Int, Class<Message>>> = [
0x01 => [
0x0001 => LoginRequest,
0x0002 => LoginResponse
]
];
private var socket:Socket;
public function new(host:String, port:Int, onConnect:Event->Void) {
this.onConnect = onConnect;
socket = new Socket();
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
//socket.endian = flash.utils.Endian.LITTLE_ENDIAN;
socket.connect(host, port);
}
private function onError(event:ErrorEvent):Void {
}
public dynamic function onConnect(event:Event):Void {
}
private function onClose(_):Void {
}
private function onSocketData(_):Void {
var family = socket.readByte();
var id = socket.readByte();
var b = new flash.utils.ByteArray();
socket.readBytes(b);
var bs = Bytes.ofData(cast b);
var packet = buildPacket(family, id);
packet.mergeFrom(bs);
receive(packet);
}
private function buildPacket(family:Int, id:Int):Message {
var packetClass = MAP[family][id];
return Type.createInstance(packetClass, []);
}
public function send(packet:Message):Void {
for (family in MAP.keys()) {
var subMap = MAP[family];
for (id in MAP.keys()) {
var packetClass = subMap[id];
if (Std.is(packet, packetClass)) {
socket.writeByte(family);
socket.writeByte(id);
var out = new BytesOutput();
packet.writeTo(out);
var bytes = out.getBytes();
socket.writeShort(bytes.length);
socket.writeBytes(cast bytes.getData());
socket.flush();
}
}
}
}
public dynamic function receive(packet:Message):Void {
L.d("Receive", packet + "");
}
}

View File

@@ -0,0 +1,13 @@
package ru.m.armageddon.core.connect;
import flash.events.Event;
import protohx.Message;
interface IConnection {
public function send(packet:Message):Void;
public dynamic function onConnect(event:Event):Void;
public dynamic function receive(packet:Message):Void;
}