【问题标题】:Reading a HTTP request with sockets on HashLink在 HashLink 上使用套接字读取 HTTP 请求
【发布时间】:2019-04-06 17:30:18
【问题描述】:

我正在尝试使用带有 HashLink (1.9.0) 的 haxe (4) 制作 HTTP 服务器,但套接字似乎不能很好地工作。

import haxe.io.Error;
import sys.net.Host;
import sys.net.Socket;

class Main {
    static public function main() {

        var _aSocketDistant = new List<Socket>();

        var _oSocketMaster = new Socket();
        _oSocketMaster.bind( new Host( 'localhost' ), 8000);
        _oSocketMaster.setBlocking( false );
        _oSocketMaster.listen( 9999 );

        while(true) {

            // Accepting socket
            var oSocketDistant = _oSocketMaster.accept();
            if ( oSocketDistant != null ) {
                trace( 'opening : ' + oSocketDistant.peer() );
                oSocketDistant.setBlocking( false );
                _aSocketDistant.add( oSocketDistant );
            }

            // Trying to read from each socket 
            for ( oSocketDistant in _aSocketDistant ) {
                try {
                    trace( oSocketDistant.read() );
                } catch ( e :Dynamic ) {
                    if ( e != Error.Blocked )
                        throw e;
                }
            }

        }
    }
}

运行这段代码,然后使用 firefox 调用 http://localhost:8000/ 得到以下信息:

Main.hx:27:打开:{主机:127.0.0.1,端口:65154}

远程套接字永远不会有任何消息要读取。 它不应该发送请求吗?

【问题讨论】:

  • 我只知道hashlink有libuv,所以我觉得可能比sys.net.Socket好。

标签: haxe hashlink


【解决方案1】:

问题似乎是read() 的使用。好像是not meant to be used on non-blocking sockets:

您的实际问题是read() 将读取整个数据。在将阻塞直到连接关闭的阻塞套接字上。在将始终引发Blocking 的非阻塞套接字上。相反,您必须使用input.readBytes,它将返回读取的字节数,然后确保您正确管理缓冲区数据。

在这种情况下,使用input.readLine() 可能是最简单的解决方案:

trace(oSocketDistant.input.readLine());

这样,我可以按预期看到 HTTP 请求:

Main.hx:20: opening : {host : 127.0.0.1, port : 50231}
Main.hx:29: GET / HTTP/1.1
Main.hx:29: Host: localhost:8008
Main.hx:29: Connection: keep-alive
Main.hx:29: Upgrade-Insecure-Requests: 1
Main.hx:29: User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Main.hx:29: DNT: 1
Main.hx:29: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Main.hx:29: Accept-Encoding: gzip, deflate, br
Main.hx:29: Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Main.hx:29: Cookie: Idea-369662de=0cbb3289-7f2c-4f82-a094-7409dba8cfb0
Main.hx:29:

【讨论】:

  • 好的,我想我现在明白了,读取不起作用可能是因为它需要流的结尾(永远不会出现),但另一方面,像 readByte 或 readLine 这样的函数会产生,因为它们只需要一个字符或一个大小来结束阅读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 1970-01-01
相关资源
最近更新 更多