90 lines
2.6 KiB
Haxe
Executable File
90 lines
2.6 KiB
Haxe
Executable File
package ru.m.connect.flash;
|
|
|
|
import flash.events.ErrorEvent;
|
|
import flash.events.Event;
|
|
import flash.events.IOErrorEvent;
|
|
import flash.events.ProgressEvent;
|
|
import flash.events.SecurityErrorEvent;
|
|
import flash.net.Socket;
|
|
import flash.utils.Endian;
|
|
import haxe.io.Bytes;
|
|
import promhx.Deferred;
|
|
import promhx.Promise;
|
|
import protohx.Message;
|
|
import ru.m.connect.IConnection;
|
|
|
|
class FlashConnection<O:Message, I:Message> extends BaseConnection<O, I> {
|
|
|
|
private var host:String;
|
|
private var port:Int;
|
|
private var socket:Socket;
|
|
|
|
public function new(host:String, port:Int, inputFactory:Class<I>) {
|
|
super(inputFactory);
|
|
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;
|
|
sendHandler.connect(_send);
|
|
}
|
|
|
|
override public function connect():Promise<IConnection<O, I>> {
|
|
socket.connect(host, port);
|
|
connectDeferred = new Deferred();
|
|
return connectDeferred.promise();
|
|
}
|
|
|
|
override public function disconnect():Void {
|
|
if (socket.connected) {
|
|
socket.close();
|
|
connected = false;
|
|
handler.emit(ConnectionEvent.DISCONNECTED);
|
|
}
|
|
}
|
|
|
|
private function onError(event:ErrorEvent):Void {
|
|
socket.close();
|
|
connected = false;
|
|
handler.emit(ConnectionEvent.ERROR(event));
|
|
if (connectDeferred != null) {
|
|
connectDeferred.throwError(event);
|
|
connectDeferred = null;
|
|
}
|
|
}
|
|
|
|
private function onConnect(_):Void {
|
|
connected = true;
|
|
handler.emit(ConnectionEvent.CONNECTED);
|
|
if (connectDeferred != null) {
|
|
connectDeferred.resolve(this);
|
|
connectDeferred = null;
|
|
}
|
|
}
|
|
|
|
private function onClose(_):Void {
|
|
socket.close();
|
|
connected = false;
|
|
handler.emit(ConnectionEvent.DISCONNECTED);
|
|
}
|
|
|
|
private function onSocketData(_):Void {
|
|
var data = new flash.utils.ByteArray();
|
|
socket.readBytes(data);
|
|
var bytes = Bytes.ofData(data);
|
|
pushData(bytes);
|
|
}
|
|
|
|
private function _send(packet:O):Void {
|
|
var bytes = PacketUtil.toBytes(packet);
|
|
socket.writeShort(bytes.length);
|
|
socket.writeBytes(bytes.getData());
|
|
socket.flush();
|
|
}
|
|
}
|