无法在不同计算机上连接Python套接字
我最近用Python写了一个小聊天程序的代码。当我在同一台电脑的不同终端上连接时,连接是没问题的。但是,当我试图从不同的电脑连接时,虽然它们在同一个Wifi网络下,却好像不行。
这是服务器的代码:
#!/usr/bin/env python
print "-"*60
print "WELCOME TO DYNASOCKET"
print "-"*60
import socket, os, sys, select
host = "192.168.1.101"
port = 8888
connlist = []
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket Successfully Created."
connlist.append(s)
s.bind((host,port))
print "Socket Successfully Binded."
s.listen(10)
print "Socket is Now Listening."
except Exception, e:
print "Error : " + str(e)
sys.exit()
def air(sock,message):
for socket in connlist:
if socket != sock and socket != s:
try:
socket.sendall(message)
except:
connlist.remove(socket)
while 1:
read_sockets,write_sockets,error_sockets = select.select(connlist,[],[])
for sock in read_sockets:
if sock == s:
conn, addr = s.accept()
connlist.append(conn)
print "Connected With " + addr[0] + " : " + str(addr[1])
else:
try:
key = conn.recv(1024)
print "<" + str(addr[1]) + ">" + key
data = raw_input("Server : ")
conn.sendall(data + "\n")
air(sock, "<" + str(sock.getpeername()) + ">" + key)
except:
connlist.remove(sock)
print "Connection Lost With : " + str(addr[1])
conn.close()
s.close()
这是客户端的脚本:
#!/usr/bin/env python
print "-"*60
print "WELCOME TO DYNASOCKET"
print "-"*60
import socket, os, sys
host = "192.168.1.101"
port = 8888
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket Successfully Created."
s.connect((host,port))
print "Connected With " + host + " : " + str(port)
except socket.error, e:
print "Error : " + str(e)
while 1:
reply = raw_input("Client : ")
s.send(reply)
message = s.recv(1024)
print "Server : " + message
s.close()
当我尝试从另一台电脑连接客户端时,我遇到了这个错误:
Error : [Errno 10060] A Connection attempt failed because the connected party
did not respond after a period of time, or established connection failed
because connected host has failed to respnd.
3 个回答
我之前也遇到过这个问题,使用ngrok创建tcp隧道对我来说很有效。你可以在这里查看它。
如果你在电脑上做简单的socket应用,只需通过 ngrok tcp <端口号>
来暴露你正在使用的端口,然后把服务器的socket绑定到localhost和暴露的端口上。客户端那边使用隧道的URL和端口号(通常看起来像 0.tcp.us.ngrok.io
和一个端口号)。
你甚至可以在免费账户上创建多个隧道(我当时就需要这样),只需指定 --region
参数即可:https://ngrok.com/docs#global-locations
我遇到了这个问题,花了很多时间才搞明白,发现(就像很多人说的@Cld)是你的防火墙阻止了连接。以下是我解决这个问题的方法:
试着在你想要连接的机器上运行服务器。
(比如说,如果你想在A机器上运行服务器,但从B机器连接,就在B机器上运行服务器。)如果你使用的是Windows系统(我不太确定Mac或Linux的情况),会弹出一个防火墙的提示框,允许你给你的程序访问私有网络的权限。
只需勾选那个选项:
“私有网络,比如我的家庭或工作网络”,然后点击允许访问。就这样!你解决了这个特定的问题。现在可以在那台机器上测试服务器,或者关闭服务器,回到你的主机器上,运行那个服务器。你应该能看到它现在可以正常工作了。
希望这对你有帮助,因为这是我第一次发帖!
补充:我还做了@Daniel在他的帖子中提到的,把s.bind改成包含'0.0.0.0'。
你把服务器只绑定到了本地,这样其他地方的连接就被阻止了。
试试这个:
s.bind(("0.0.0.0",port))