为什么节点.jsHTTP服务器不响应来自Python的请求?

2024-04-16 10:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个正在工作的HTTP节点.js服务器。在

然后我在python上创建了一个程序,它使用socket模块连接到上面的服务器

请暂时不要介意try和except语句。该代码的connectTO()函数与任何其他代码一样,只是它处理一些错误,与服务器连接。然后程序发送消息"hello"。接下来在while循环中,它反复等待一个答案,当它收到一个答案时,它会打印它。在

当我连接到js节点来自python的http服务器,我确实收到消息:

"You have just succesfully connected to the node.js server"

看看我的命令是成功的。我的问题是,当一个请求被发送到服务器时,它应该输出一条消息回来,但是它没有

我还尝试向服务器发送消息,在这种情况下,服务器将返回以下消息:

HTTP/1.1 400 Bad Request

那么为什么服务器没有响应请求呢?为什么要拒绝他们?在

Python客户端:

^{pr2}$

节点.jsHTTP服务器:

function onRequest(req, res) {
    var postData = "";
    var pathname = url.parse(req.url).pathname;

    //Inform console of event recievent
    console.log("Request for "+pathanme+" received.");

    //Set the encoding to equivelant one used in html
    req.setEncoding("utf8");

    //add a listener for whenever info comes in and output full result
    req.addListener("data", function(postDataChunk) {
        postData += postDataChunk;
        console.log("Received POST data chunk: '"+postDataChunk+"'");
    });

    req.addListener("end", function() {
        route(handle, pathname, res, frontPage, postData);
    });

};

http.createServer(onRequest).listen(port,ip);
console.log("Server has started.");

我的一些研究

我还应该注意到,经过一些研究,HTTP服务器似乎接受HTTP请求,但我不明白Wikipedia上的大部分内容。这就是服务器没有响应的原因吗?如何在仍然使用socket模块的情况下修复它。在

还有很多关于堆栈溢出的类似问题,但是没有一个能帮助我解决问题。One of them描述了我的问题,唯一的答案是关于“握手”。谷歌在这里也毫无意义,但据我所知,这只是服务器和客户端之间的反应,它定义了协议的内容。这可能是我缺少的吗?我如何实现它?在

其中一些问题还使用了我还没有准备好使用的模块,比如websocket。或者它们描述了服务器连接到客户机的方式,这可以通过直接调用python代码或从连接到它来完成节点.js快车。我希望客户机通过python中的socket模块连接到HTTP服务器。为了将来寻找这种东西的游客,这里有一些问题:


这个问题的答案很明显,但事实上,这个问题并没有解决。对服务器不太了解的人可能会错过它: how to use socket fetch webpage use python


Tags: 模块to答案代码服务器http消息节点
1条回答
网友
1楼 · 发布于 2024-04-16 10:26:49

您需要构造一个HTTP请求。在

示例:GET / HTTP/1.1\n\n

试试这个:

from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import threading, socket, time, sys

s = socket.socket(AF_INET,SOCK_STREAM)

def connectTO(host,port):
    connect = False
    count = 0
    totalCount = 0
    while connect!= True:
        try:
            s.connect((host,port))
            connect = True
            print("You have just succesfully connected to the node.js server")
        except OSError:
            count += 1
            totalCount += 1
            if totalCount == 40 and count == 4:
                print("Error: 404. Connection failed repeatedly")
                sys.exit(0)
            elif count == 4:
                print("Connection failed, retrying...")
                count = 0
            else:
                pass          

connectTO("IP_OF_NODE.jS_SERVER_GOES_HERE",777)
message = "GET / HTTP/1.1\n\n"
s.send(message.encode("utf-8"))

while True:
    try:
        data, addr = s.recvfrom(1024)
        if data == "":
            pass
        else:
            print(data.decode())
    except ConnectionResetError:
        print("it seems like we can't reach the server anymore..")
        print("This could be due to a change in your internet connection or the server.")
    s.close()

阅读this以了解有关HTTP的更多信息。在

现在,我建议使用this python lib来做你想做的事情。这让事情变得容易多了。但是,如果您100%地使用原始套接字,那么您应该让节点服务器也使用原始套接字。(假设您将只通过python进行连接)。Here is an excellent tutorial

相关问题 更多 >