87 lines
2.3 KiB
Haxe
Executable File
87 lines
2.3 KiB
Haxe
Executable File
package ru.m.connect.flash;
|
|
|
|
import ru.m.connect.IConnection.IConnectionHandler;
|
|
import flash.utils.Endian;
|
|
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 extends BaseConnection {
|
|
|
|
private var host:String;
|
|
private var port:Int;
|
|
private var socket:Socket;
|
|
|
|
public function new(host:String, port:Int) {
|
|
super();
|
|
this.host = host;
|
|
this.port = port;
|
|
connected = false;
|
|
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 = Endian.LITTLE_ENDIAN;
|
|
}
|
|
|
|
override public function connect():Void {
|
|
socket.connect(host, port);
|
|
}
|
|
|
|
override public function disconnect():Void {
|
|
if (socket.connected) {
|
|
socket.close();
|
|
connected = false;
|
|
handler.dispatch(function(h) h.onDisconnected());
|
|
}
|
|
}
|
|
|
|
private function onError(event:ErrorEvent):Void {
|
|
socket.close();
|
|
connected = false;
|
|
handler.dispatch(function(h) h.onError(event));
|
|
}
|
|
|
|
private function onConnect(_):Void {
|
|
connected = true;
|
|
handler.dispatch(function(h) h.onConnected());
|
|
}
|
|
|
|
private function onClose(_):Void {
|
|
socket.close();
|
|
connected = false;
|
|
handler.dispatch(function(h) h.onDisconnected());
|
|
}
|
|
|
|
private function onSocketData(_):Void {
|
|
try {
|
|
var b = new flash.utils.ByteArray();
|
|
socket.readBytes(b);
|
|
var bs = Bytes.ofData(cast b);
|
|
pushData(bs);
|
|
} catch (error:Dynamic) {
|
|
handler.dispatch(function(h) h.onError(error));
|
|
}
|
|
}
|
|
|
|
override public function send(packet:Message):Void {
|
|
super.send(packet);
|
|
var meta = builder.packetMeta(packet);
|
|
socket.writeByte(meta.family);
|
|
socket.writeByte(meta.id);
|
|
var out = new BytesOutput();
|
|
packet.writeTo(out);
|
|
var bytes = out.getBytes();
|
|
socket.writeShort(bytes.length);
|
|
socket.writeBytes(cast bytes.getData());
|
|
socket.flush();
|
|
}
|
|
} |