错误是因为sys.stdin不是Windows上的套接字。这降低了select的有用性,因此我们被迫使用线程。在
以下是适用于Windows的最小正确客户端实现:
聊天_客户端.py在import sys
import socket
import select
from threading import Thread
def receive(s):
"""Handles receiving of messages."""
while True:
try:
ready = select.select([s], [], [])
if ready[0]:
data = s.recv(1024)
if not data:
print '\nDisconnected from chat server'
sys.exit()
else:
# print data
sys.stdout.write(data)
sys.stdout.write('[Me] ')
sys.stdout.flush()
except OSError: # Possibly client has left the chat.
break
def chat_client2():
if len(sys.argv) < 3:
print 'Usage : python chat_client.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try:
s.connect((host, port))
except:
print 'Unable to connect'
sys.exit()
print 'Connected to remote host. You can start sending messages'
sys.stdout.write('[Me] ')
sys.stdout.flush()
receive_thread = Thread(target=receive, args=(s,))
receive_thread.daemon = True
receive_thread.start()
while 1:
# user entered a message
msg = sys.stdin.readline()
s.send(msg)
sys.stdout.write('[Me] ')
sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client2())