【发布时间】:2012-10-11 04:35:15
【问题描述】:
我的这些客户端和服务器代码有问题,我一直收到 [Errno 10061] 无法建立连接,因为目标机器主动拒绝了它
我在带有 Windows XP SP3 的虚拟机上运行服务器,在 Windows 7 64 位上运行客户端,我的 python 版本是 2.7.3。我想知道的是我应该如何编辑代码以在不同的网络上使用客户端和服务器!谢谢!
服务器:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = '0.0.0.0' # Get local machine name
port = 12345 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
while True:
msg = c.recv(1024)
print addr, ' >> ', msg
msg = raw_input('SERVER >> ')
c.send(msg);
#c.close() # Close the connection
客户:
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
print 'Connecting to ', host, port
s.connect((host, port))
while True:
msg = raw_input('CLIENT >> ')
s.send(msg)
msg = s.recv(1024)
print 'SERVER >> ', msg
#s.close # Close the socket when done
PS : 代码来自网络。
【问题讨论】:
-
主动拒绝表示服务器机器的防火墙阻止了连接,可能与代码无关。
-
防火墙已关闭:/ 仍然出现错误
-
您的 VM 来宾如何连接到网络?通过 NAT + 端口转发还是通过桥接模式?
-
通过 NAT + 端口转发!