sys.net.Socket 是适用于九个 Haxe 目标的主要套接字实现:Python、HashLink、Neko、Java、Macro、C++、Lua、PHP 和 C#。
以线程方式使用这些套接字的一种方法以及进一步的背景是provided here.
但是,Haxe 文档并没有明确说明套接字如何在非阻塞模式下工作。下面的示例是针对客户端的,可能会在游戏中使用——其他用法应该类似。为此,请创建一个套接字并以常规方式连接它:
var socket = new Socket();
try
{
socket.connect(new Host('example.com'), 80);
}
catch (e: Dynamic)
{
// handle connection errors...
}
成功建立连接后,应关闭阻塞模式:
socket.setBlocking(false);
然后我们可以使用 socket.input 从套接字中读取数据,但需要注意的是我们必须使用 try-catch 异常处理:
var out: String = '';
try
{
// could also use .input.readByte(), .input.readDouble() etc.
// .read() doesn't work, however.
out = socket.input.readLine();
}
catch (e: Dynamic) // catch all types of errors
{
// can handle specific types of exceptions here.
}
由于套接字是非阻塞的,我们将不得不在循环中调用它。
每次我们调用它时,我们都会得到一个可以忽略的“操作将阻塞”异常。此异常用于在我们等待数据时中断从套接字读取以在循环中执行其他操作。
以类似的方式,我们可以写入套接字:
var msg: String = 'hello world!\r\n';
try
{
// could also use socket.write(msg) or socket.output.writeByte() etc...
socket.output.writeString(msg);
}
catch (e: Dynamic) { }
我们还可以做具体的异常处理:
catch (e: Dynamic)
{
// end of stream
if (Std.is(e, haxe.io.Eof) || e == haxe.io.Eof)
{
// close the socket, etc.
}
else if (e == haxe.io.Error.Blocked)
{
// not an error - this is still a connected socket.
break;
}
else
{
trace(e);
}
}