此Python代码存在问题。请帮我。谢谢
import sys
import socket
import select
HOST = 'sys.ase.ro'
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 6508
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
SOCKET_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
while 1:
ready_to_read, ready_to_write, in_error = select.select(SOCKET_LIST, [], [], 0)
for sock in ready_to_read:
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
else:
try:
data = sock.recv(RECV_BUFFER)
if data:
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
# broadcast chat messages to all connected clients
def broadcast(server_socket, sock, message):
for socket in SOCKET_LIST:
if socket != server_socket and socket != sock:
try:
socket.send(message)
except:
socket.close()
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "__main__":
sys.exit()
错误看起来像:
Traceback (most recent call last): File
"C:/Users/Admin/PycharmProjects/untitled/chat_server.py", line 90, in
<module>
sys.exit(chat_server()) File "C:/Users/Admin/PycharmProjects/untitled/chat_server.py", line 20, in
chat_server
server_socket.bind((HOST,PORT)) File "C:\Python27\Lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args) socket.error: [Errno 10049] The requested address is not valid in its context
答案 0 :(得分:0)
您正在尝试将套接字绑定到远程地址。 来自windows documentation:
bind函数将本地地址与套接字相关联。
改为使用connect:
server_socket.connect((HOST, PORT))
答案 1 :(得分:0)
我弄清楚为什么它不起作用 我的代码失败的原因是因为我试图绑定到外部主机名。 我的机器不知道该主机名,因此错误消息。我在localhost中对其进行了更改,并且可以正常工作。