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

标签 python sockets

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

最佳答案

您只将您的服务器绑定(bind)到本地主机,因此来自其他主机的连接将被阻止。

尝试:

s.bind(("0.0.0.0",port))

关于python - 无法连接不同计算机上的 Python 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25584485/

相关文章:

python - "NameError: global name is not defined"当 PDB 认为已定义时抛出

python - rdflib "repeat node-elements"OWL/XML 文件解析错误

c# - 关闭 TCP 套接字 - 调试器关闭连接时有何不同

sockets - FastCGI/SCGI前叉

c++ - 如何使用 boost asio 通过 UDP 套接字发送 std::vector of unsigned char?

python - 为什么 "not"运算符比 python 中的常规条件更快?

python - Django 数据库错误 : missing table social_auth_usersocialauth when social_auth is not installed

python - 在 Python PDB 中,如何列出当前文件以外的文件的源代码?

Java套接字/序列化,对象不会更新

c - UDP 接收错误 : Connection refused