exceptionwebsockethaxeopenflneko

Neko server, Neko/OpenFL client: std@socket_read exception


I'm beginner in the sockets and I'm writing a simple app to get started with. Server.hx:

package;

import neko.Lib;
import sys.net.Host;
import sys.net.Socket;

class Main 
{

    static function main() 
    {
        var s:Socket = new Socket();
        s.bind(new Host("localhost"), 5000);
        s.listen(1);
        trace("Server started");
        while (true)
        {
            var c:Socket;
            var data:String;
            c = s.accept();
            trace("Accepted peer: " + c.peer().host.ip);
            c.write("Hi");

            while (true)
            {
                c.waitForRead();
                data = c.input.readLine();
                if (data.charAt(0) == "M")
                    trace(data.split(":")[1]);
                else if (data.charAt(0) == "Q")
                {
                    c.close();
                    break;
                }
                else
                {
                    trace("ERROR! CORRUPTED DATA");
                    c.close();
                    break;
                }
            }
        }
    }

}

Client.hx:

import openfl.display.Sprite;
import openfl.Lib;
import sys.net.Host;
import sys.net.Socket;

class Main extends Sprite 
{

    public function new() 
    {
        super();

        var s:Socket = new Socket();
        var data:String; 
        s.connect(new Host("localhost"), 5000);
            //s.waitForRead();
            //data = s.input.readLine();
            //trace(data);

            s.write("M:Test message");
            s.write("Q");
            s.close();
    }

}

When I launch the server, It works fine, but when I connect to it via client, it prints client's ip and then throws an exception std@socket_read. It also says that this exception was thrown at this line of code:

data = c.input.readLine();

P. S. I've commented "Hi" handling because openFL seems not to support long-lasting loops like one that was declared in Socket.waitForRead() and the application will stop responding if I compile it with it. It's also a problem, that I don't know how to solve, but I want to get rid of std@socket_read exception first


Solution

  • Both the read error and the blocking you experienced are caused by missing newlines at the end of all exchanged messages.

    The error is caused by the server failing to acknowledge the Q command, due to the missing newlines.

    The blocking is due to c.input.readLine() waiting (forever) until it reaches a newline or the EOF.