Something I’ve stumbled on today, with respect to the openfl.net.socket
class. I suspect the protocol used by the Socket changes depending on the build target. So for HTML5, it’s using WebSockets, but for all others, I’m not sure what it’s using, perhaps a standard TCP socket?
I have a basic WebSocket server running in Node.js for testing. It’s able to receive my app’s data so long as I build to HTML5.
If I build to Neko, HashLink, Windows (C++), Flash, my WebSocket server seems to receive no data. The Windows build actually hangs in the attempt to connect. Is this expected behaviour, am I right in assuming the other targets are using a protocol incompatible with WebSocket? Is it possible/necesarry to force WebSocket on other build targets?
My basic Node.js WebSocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 443 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('%s', message);
});
ws.send('pong');
});
My OpenFL app:
package;
import openfl.display.Sprite;
import openfl.events.Event;
import openfl.events.IOErrorEvent;
import openfl.events.ProgressEvent;
import openfl.events.SecurityErrorEvent;
import openfl.net.Socket;
import openfl.utils.ByteArray;
class Main extends Sprite {
private var socket:Socket;
public function new() {
super();
socket = new Socket("localhost", 443);
socket.addEventListener(Event.CONNECT, socketConnect);
socket.addEventListener(ProgressEvent.SOCKET_DATA, socketData);
socket.addEventListener(Event.CLOSE, socketClosed);
socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
}
private function socketConnect(e:Event):Void {
socket.writeUTFBytes("ping");
socket.flush();
}
private function socketData(e:ProgressEvent):Void {
var bytes:ByteArray = new ByteArray();
socket.readBytes(bytes);
if (bytes.length == 0)
return;
trace(bytes.readUTFBytes(bytes.bytesAvailable));
}
private function socketClosed(e:Event):Void {
trace("Socket closed by server.");
}
private function ioErrorHandler(e:IOErrorEvent):Void {
trace("Socket IOError: " + e.toString());
}
private function securityErrorHandler(e:SecurityErrorEvent):Void {
trace("Socket SecurityError: " + e.toString());
}
}