How to use Haxe sockets in a cross-platform manner without blocking?

Most of the tutorials related to using sockets with the Haxe toolkit are based on the use of threads, which are platform-specific. This is because sockets are blocked by default, which makes them unsuitable for many types of applications, including games.

I know that there is a non-blocking mode, but I can not make it function without causing an exception.

How to use sockets in cross-platform mode without relying on threads?

+4
source share
1 answer

Sys.net.Socket - , Haxe: Python, Neko, Java, , ++, Lua, PHP #.

, .

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);
    }
}
+5

Source: https://habr.com/ru/post/1653436/


All Articles