使用ngrok访问python服务器(Web服务器) [英] Accessing python server (web server) using ngrok

查看:130
本文介绍了使用ngrok访问python服务器(Web服务器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python网络服务器代码.

I have a python network server code.

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()

我有一个访问服务器的客户端代码.

I have a client code that accesses the server.

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)

当我执行服务器和客户端时,它与预期的输出正常工作.

It works fine with the expected output when I executed the server and client.

Socket successfully created
('Received', "'HTTP/1.1 200 OK\\nContent-Type: text/html; charset=utf-8\\n\\n<H1>Hello, World!</H1>\\n'")

然后,我尝试使用 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访问Web服务器.

Using curl, I could access the webserver with ngrok.

> curl http://d2fccf7f.ngrok.io 
<H1>Hello, World!</H1>

但是,当我尝试使用相同的客户端代码进行少量修改时,服务器似乎没有响应.

However, when I tried to use the same client code with minor modifications, the server doesn't seem to respond.

import socket
ip = socket.gethostbyname('d2fccf7f.ngrok.io')
print(ip)
HOST = ip
PORT = 5000 
# the rest of the code is the same

我将PORT更改为80或8080,但是我得到了相同的结果.

I changed the PORT to 80 or 8080, but I had same results.

可能是什么问题?

推荐答案

从oguz ismail的提示中,我制作了以下REQUEST标头使其起作用.我看到主机信息和空白行应为必填项.

From oguz ismail's hint, I made the following REQUEST header to make it work. I see that the Host information and blank line should be required.

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'''
    ...

这篇关于使用ngrok访问python服务器(Web服务器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆