gpt4 book ai didi

haxe - 在 HashLink 上使用套接字读取 HTTP 请求

转载 作者:行者123 更新时间:2023-12-02 00:54:23 28 4
gpt4 key购买 nike

我正在尝试使用带有 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;
}
}

}
}
}

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

Main.hx:27: opening : {host : 127.0.0.1, port : 65154}

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

最佳答案

问题似乎出在 read() 的使用上。看来这是not meant to be used on non-blocking sockets :

Your actual issue is that read() will read the whole data. On a blocking socket that would block until the connection is closed. On a non blocking socket that will always raise Blocking. You instead have to use input.readBytes which will return the number of bytes read, and then make sure you correctly manage your buffer data.

在这种情况下,使用 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:

关于haxe - 在 HashLink 上使用套接字读取 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55551674/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com