无法连接不同计算机上的 Python 套接字

2023-12-22

我最近用 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.

您仅将服务器绑定到本地主机,以便阻止来自其他主机的连接。

Try:

s.bind(("0.0.0.0",port))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法连接不同计算机上的 Python 套接字 的相关文章

随机推荐