【问题标题】:Why can I only connect to myself through socket? (python)为什么我只能通过socket连接到自己? (Python)
【发布时间】:2015-01-14 10:11:42
【问题描述】:

我正在尝试制作简单的客户端-服务器程序,但它仅在我在同一台计算机上运行两个脚本时才有效,当将其移动到另一台计算机时 - 它根本不建立连接。

服务器:

__author__ = 'user-pc'
import socket               # Import socket module

s = socket.socket()         # Create a socket object
host="0.0.0.0"              # Bind with everyone
port = 13254                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

客户:

__author__ = 'user-pc'
import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = "192.168.10.4"       # Server Ip
port = 13254                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

你能帮我解决这个问题吗? 谢谢。

【问题讨论】:

  • 服务器端口是否对客户端开放? iptablesfirewalls 等等……
  • 谷歌搜索“如何在 上打开端口?”
  • 你的服务器和客户端在同一个网络吗?它们是如何连接到网络的?在运行您的程序之前,请尝试从客户端 ping 服务器以确保您已连接到服务器。如果您收到回复,则不是网络问题。现在运行你的程序,然后尝试 ping 13254 端口,如果没有得到回复,则可能是防火墙。

标签: python sockets client server


【解决方案1】:

当您在服务器上运行这两个脚本时它可以工作,很可能您的端口已关闭。

验证您的端口是否打开。去这个网站:http://www.canyouseeme.org/

输入您的端口和 IP。您的端口很可能已关闭。这将验证这一点。假设您的端口已打开,您需要查看 dmg 在上面的评论中推荐的防火墙设置。那么,就不再是python的问题了!

【讨论】:

  • 两台电脑都需要打开端口吗?或者只有服务器
  • 两者。但我怀疑服务器端口比客户端端口更可能关闭。
猜你喜欢
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 2016-04-16
  • 2013-06-07
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多