[英]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.