简体   繁体   中英

python socket connecting to ngrok server

So I'm a bit new to python servers and I have made a simple program that sends a message to a server. It works when I set the host as 192.168.xx but I have tried to use ngrok so that way I can access the server if I'm on another network. Howver I can't seem to figure out how to get it to work. This is also probably not the best way to do it so if anyone could suggest a better way that would be great but right now I have:

A server that's hosted on 192.168.xx:8080

An ngrok tunnel that forwards to my ip

and a client program that sends data to that ngrok address

Here is the host code:

import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
if __name__ == "__main__":
    HOST, PORT = "192.169.x.x", 8080
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

And here is the client:

import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    ip = socket.gethostbyname('http://urlgoeshere.ngrok.io')
    print(ip)
    sock.connect((ip, 8080))
    sock.sendall(bytes("hello" + "\n", "utf-8"))

The ngrok is:

Forwarding http://urlhere.ngrok.io -> http://192.168.xx

Note: this worked when instead of using ngrok I used my computer IP so I know its not a problem with the host

No errors but the server does not seem to respond

Thanks!

I'm not familiar with ngrok, but hosting your code locally I found changing HOST in the server to:

HOST, PORT = "0.0.0.0", 8080

...or the actual local ip gave me the expected response.

Sockets work on tcp protocol, but you try to use http. I solved this problem by LogMeIn Hamachi. It works with sockets perfectly. You can also use ngrok, but you need to upgrade to Pro or Business plan to use tcp.

You can read about pyngrok here if you need it: https://pyngrok.readthedocs.io/en/latest/integrations.html#python-tcp-server-and-client

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM