[英]Accessing python server (web server) using ngrok
我有一个 python 网络服务器代码。
import socket
HOST, PORT = '', 5000
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Serving HTTP on port %s ...' % PORT)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print(request)
http_response = """\
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<H1>Hello, World!</H1>
"""
client_connection.sendall(http_response.encode())
client_connection.close()
我有一个访问服务器的客户端代码。
import socket
HOST = '127.0.0.1'
PORT = 5000 # The port used by the server
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
s.connect((HOST, PORT))
s.sendall('GET /')
data = s.recv(1000)
print('Received', repr(data))
s.close
except socket.error as err:
print "socket creation failed with error %s" %(err)
当我执行服务器和客户端时,它与预期的输出一起工作正常。
Socket successfully created
('Received', "'HTTP/1.1 200 OK\\nContent-Type: text/html; charset=utf-8\\n\\n<H1>Hello, World!</H1>\\n'")
然后,我尝试使用ngrok.
执行 python 服务器ngrok.
Session Status online
Account ...
Version 2.3.34
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://d2fccf7f.ngrok.io -> http://localhost:5000
使用curl
,我可以使用 ngrok 访问网络服务器。
> curl http://d2fccf7f.ngrok.io
<H1>Hello, World!</H1>
但是,当我尝试使用相同的客户端代码并稍作修改时,服务器似乎没有响应。
import socket
ip = socket.gethostbyname('d2fccf7f.ngrok.io')
print(ip)
HOST = ip
PORT = 5000
# the rest of the code is the same
我将端口更改为 80 或 8080,但结果相同。
可能有什么问题?
我可以建议尝试像pyngrok
这样的pyngrok
来为你以编程方式管理你的ngrok
隧道吗? 完全公开,我是它的开发者。 套接字和其他 TCP 示例在此处。
根据 oguz ismail 的提示,我制作了以下 REQUEST 标头以使其工作。 我看到应该需要主机信息和空行。
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
s.connect((HOST, PORT))
header = '''GET / HTTP/1.1\r\nHost: d2fccf7f.ngrok.io\r\n\r\n'''
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.