2
我最近爲Python中的一個小型聊天程序編寫了代碼。當我將它們連接到同一系統上的不同終端時,套接字連接良好。但是,當我通過同一個Wifi網絡連接的不同計算機連接它們時,似乎也不會發生這種情況。無法連接不同計算機上的Python套接字
這裏的服務器代碼:
#!/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.
不是真的具體到蟒蛇。你確定你沒有防火牆阻止流量? – Cld 2014-08-30 16:30:07
通常會出現這樣的問題,因爲路由器沒有像您期望的那樣路由某些(大部分)端口。如果將端口號設置爲80(HTTP端口)並再次嘗試,它是否仍然失敗?我還假設你在那裏指定的「主機」計算機上運行服務器,而不是試圖將客戶機連接到錯誤的地址。 – Anthony 2014-08-30 16:30:16
我不認爲防火牆阻止了任何流量。我也嘗試將端口更改爲80.但它仍顯示相同的錯誤。 :( – 2014-08-30 17:32:48