我正在使用聊天客户端,这是我的代码:
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教程来做这个(http://www.bogotobogo.com/python/python_network_programming_tcp_server_client_chat_server_chat_client_select.php)所以它可能与此有关。
答案 0 :(得分:0)
我知道这已经过时了但它链接到的页面首先出现在我的搜索python聊天服务器中。由于我需要使用一些可用的代码,我认为其他人可能会喜欢更新的chat_client.py,以便与http://www.bogotobogo.com/python/python_network_programming_tcp_server_client_chat_server_chat_client_select.php
上非常简单的服务器一起使用错误是因为sys.stdin
不是Windows上的套接字。这降低了select
的有用性,因此我们不得不使用线程。
这是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())