我有一个有效的HTTP node.js服务器。
然后我在python上创建了一个程序,它使用套接字模块连接到上面的服务器
请暂时不要介意尝试和除外的陈述。代码的"hello"
函数只是像任何其他代码一样连接到服务器,但它处理一些错误除外。然后程序发送消息"You have just succesfully connected to the node.js server"
。接下来在while循环中它会反复等待答案,当它收到答案时,它会打印出来。
当我从python连接到Node.js http服务器时,我收到消息:
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 = "hello"
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()
如果查看我的代码,则意味着s.connect(())命令成功。我的问题是,当一个请求发送到服务器时,它应该输出一条消息,但它没有。
我还尝试向服务器发送消息,在这种情况下服务器发回以下消息:
HTTP / 1.1 400错误请求
那么为什么服务器没有响应请求呢?为什么拒绝他们?
Python客户端:
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.");
Node.js HTTP服务器:
socket
我还应该注意到,经过一些研究,似乎HTTP服务器接受了HTTP请求,但我不了解维基百科上的大部分内容。这是服务器没有响应的原因吗?如何在仍使用websocket
模块时解决此问题。
Stack Overflow上也有很多类似的问题,但没有一个能帮我解决问题。 One of them描述了我的问题,唯一的答案是"握手"。 Google在这里也毫无意义,但据我所知,它只是服务器和客户端之间的反应,它定义了协议的内容。这可能是我错过的,我该如何实现呢?
其中一些问题也使用我尚未准备好使用的模块,如$user->attendance
。或者它们描述了服务器连接到客户端的方式,这可以通过直接调用python代码或从Node.js express连接到它来完成。我想通过python中的套接字模块将客户端连接到HTTP服务器。为了寻找这样的东西的未来访客,这里有一些问题:
这个答案实际上看起来并不明显,但也只用相关代码解决了问题。那些对服务器不太了解的人可能会错过它: how to use socket fetch webpage use python
答案 0 :(得分:2)
您需要构建一个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