Python聊天错误
我正在使用聊天客户端,以下是我的代码:Python聊天错误,python,sockets,Python,Sockets,我正在使用聊天客户端,以下是我的代码: import sys import socket import select def run(): host = "127.0.0.1" port = 8008 buffer = 4096 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(5) try: s.connect((host, port))
import sys
import socket
import select
def run():
host = "127.0.0.1"
port = 8008
buffer = 4096
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
try:
s.connect((host, port))
except:
print("Connection failed.")
#exit
print("Connected to " + host)
sys.stdout.write('[Me] '); sys.stdout.flush()
while True:
sockets = [sys.stdin, s]
ready_to_read, ready_to_write, in_error = select.select(sockets, [], [])
for sock in ready_to_read:
if sock == s:
data = sock.recv(buffer)
if not data:
print("Disconnected.")
#exit
else:
sys.stdout.write(data)
sys.stdout.write('[Me] '); sys.stdout.flush()
else:
msg = sys.stdin.readline()
s.send(msg)
sys.stdout.write('[Me] '); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(run())
但当我运行它时,服务器也在运行,如果您需要代码,请告诉我,它会给我以下错误:
C:\Python34\python.exe C:/Dev/Python/Chat/Client/main.py
Traceback (most recent call last):
Connected to 127.0.0.1
File "C:/Dev/Python/Chat/Client/main.py", line 44, in <module>
[Me] sys.exit(run())
File "C:/Dev/Python/Chat/Client/main.py", line 26, in run
ready_to_read, ready_to_write, in_error = select.select(sockets, [], [])
OSError: [WinError 10038] An operation was attempted on something that is not a socket
Process finished with exit code 1
顺便说一句,我按照一个旧的Python 2教程制作了这个,因此它可能与此有关。我知道这是旧的,但它链接到的页面在我搜索Python聊天服务器时首先出现。由于我需要一些工作代码来使用,我想其他人可能会喜欢一个更新的chat_client.py,以便在
错误是因为sys.stdin不是Windows上的套接字。这降低了select的有用性,因此我们不得不使用线程
以下是适用于Windows的最低限度的正确客户端实现:
chat_client.py
我猜sys.stdin不是windows中的套接字,无法选择?我认为此错误与windows中的select实现有关。检查此处-允许空序列,但三个空序列的接受取决于平台。众所周知,它可以在Unix上工作,但不能在Windows上工作。
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())