[英]python socket not connecting to web server
I'm trying use the python socket
module to connect to an ngrok server.我正在尝试使用 python
socket
模块连接到 ngrok 服务器。 If I put the ngrok into my browser it connects properly so the problem is somewhere with my client code.如果我将 ngrok 放入浏览器,它会正确连接,因此问题出在我的客户端代码的某个地方。 Here is the server code:
这是服务器代码:
#server.py
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
if __name__ == "__main__":
HOST, PORT = "192.168.86.43", 8080
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
And here is the client:这是客户端:
#client.py
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(("http://urlhere.ngrok.io", 8080))
sock.sendall(bytes("Hello" + "\n", "utf-8"))
Thanks!谢谢!
In general you should be able to connect to any globally available address or DNS name, ensuring there is no network restrictions on the way.一般来说,您应该能够连接到任何全球可用的地址或 DNS 名称,确保途中没有网络限制。 However you have to listen on the address that is locally available for global routing if you are communicating across the Internet.
但是,如果您通过 Internet 进行通信,则必须侦听本地可用于全局路由的地址。
As for particular code, there are 2 issues:至于具体的代码,有两个问题:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(("localhost", 8080))
sock.sendall(bytes("Hello" + "\n", "utf-8"))
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 8080
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
I'm trying use the python socket
module to connect to an ngrok server.我正在尝试使用 python
socket
模块连接到 ngrok 服务器。 If I put the ngrok into my browser it connects properly so the problem is somewhere with my client code.如果我将 ngrok 放入浏览器,它会正确连接,因此问题出在我的客户端代码的某个地方。 Here is the server code:
这是服务器代码:
#server.py
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
if __name__ == "__main__":
HOST, PORT = "192.168.86.43", 8080
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
And here is the client:这是客户:
#client.py
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(("http://urlhere.ngrok.io", 8080))
sock.sendall(bytes("Hello" + "\n", "utf-8"))
Thanks!谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.