Python:通过套接字在两台计算机之间发送数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14007227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: sending data between two computers via sockets
提问by Piotr Dabkowski
I am working on a script that would transmit the data between two distinct computers with access to the internet. I am using python's socket standard module. It works fine when I run both client and server on single computer but I am not able to make the things work when they run on different computers.
我正在编写一个脚本,可以在两台可以访问互联网的不同计算机之间传输数据。我正在使用 python 的套接字标准模块。当我在单台计算机上运行客户端和服务器时它工作正常,但是当它们在不同的计算机上运行时我无法使它们工作。
Here is a part of my server code:
这是我的服务器代码的一部分:
import socket, time,os, random
class Server():
def __init__(self,Adress=('',5000),MaxClient=1):
self.s = socket.socket()
self.s.bind(Adress)
self.s.listen(MaxClient)
def WaitForConnection(self):
self.Client, self.Adr=(self.s.accept())
print('Got a connection from: '+str(self.Client)+'.')
s = Server()
s.WaitForConnection()
And here is a part of my client code:
这是我的客户端代码的一部分:
import socket
class Client():
def __init__(self,Adress=("Here is the IP of the computer on which the \
server scrip is running",5000)):
self.s = socket.socket()
self.s.connect(Adress)
c = Client()
When I run these scripts on two different computers with internet access the client is unable to connect and raises an error and the server is waiting for connections forever.
当我在两台可以访问 Internet 的不同计算机上运行这些脚本时,客户端无法连接并引发错误,服务器一直在等待连接。
What am I doing wrong?
我究竟做错了什么?
采纳答案by Daniel Figueroa
This does probably not have to do with your code which looks okay. I rather think that this is a problem with the IP addresses that you're using.
这可能与您看起来没问题的代码无关。我宁愿认为这是您使用的 IP 地址的问题。
If the computers are on different networks you need to make sure that the IP address that you're passing is the one accessible to the net. Basically what this means is that if the IP you're using starts with 192.168.?.? then you're using the wrong IP.
如果计算机位于不同的网络上,您需要确保您传递的 IP 地址是网络可访问的 IP 地址。基本上这意味着如果您使用的 IP 以 192.168.?. 开头?那么你使用了错误的IP。
You can easily check this by running the command:
(windows): ipconfig
(linux): ifconfig
您可以通过运行以下命令轻松检查:
(windows): ipconfig
(linux): ifconfig
If you're using a correct IP address then I'd check my router settings and/or firewall settings which may very well block the port number that you're trying to use.
如果您使用的是正确的 IP 地址,那么我会检查我的路由器设置和/或防火墙设置,它们很可能会阻止您尝试使用的端口号。

