gpt4 book ai didi

python - 使用python在两个不同网络上的服务器和客户端?

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:59 25 4
gpt4 key购买 nike

我有这两个 python 脚本。

服务器:

#!/bin/env python

#--*-- coding:UTF-8 --*--

import socket
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input("Ip : ")
port = int(input("Port : "))
connexion.connect((host, port))
print("The connection with {} is done.".format(host, port))
started = True

while started:
choice = int(input(" [1] Command\n [2] Leave\n > "))
if choice == 1:
command = input(" Command : ")
connexion.send(command.encode())
retour = connexion.recv(1024).decode('latin1')
print(retour)

if choice == 2:
connexion.send("exit")
connexion.close()
break

和客户:

#!/bin/env python

#--*-- coding:UTF-8 --*--

import socket
import subprocess

connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 631
connexion.bind((host,port))
connexion.listen(5)
connexion_client, infos_connexion = connexion.accept()
started = True

while started:
rcv_cmd = connexion_client.recv(1024)
rcv_cmd = rcv_cmd.decode()
if rcv_cmd != "exit":
cmd = subprocess.Popen(rcv_cmd, shell=true, stdout = subprocess.PIPE, stderr =subprocess.PIPE, stdin = subprocess.PIPE )
out = cmd.stdout.read() + cmd.sdterr.read()
connexion_client.send(out)
else:
started = False
conexion.close()
exit

这两个脚本在我的本地网络上工作得很好,但是如果我想在两个不同的网络上使用它,我该怎么做呢?关于如何学习如何做到这一点,您有任何链接/提示吗?

最佳答案

要实现这两个服务器之间的数据传输,您需要 port forward运行服务器的计算机。为此,您需要访问路由器的控制面板。然后指令根据你的路由器而有所不同,但是你需要告诉路由器将服务器的本地IP和端口转发到公共(public)IP和端口。

之后,您应该能够使用服务器路由器的公共(public) IP 从客户端连接到您的服务器。

关于python - 使用python在两个不同网络上的服务器和客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57859616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com