所以我正在学习socket编程,并编写了一个漂亮的小聊天服务器。我遇到的问题是我的客户端无法同时读写。我不太清楚如何设置它。
这就是我到目前为止所做的,我希望read()和write()能够同时运行(这不是关于同时读写的问题 - 它是关于能够在输入时接收消息( )等待用户输入。):
import socket
import threading
class Client(threading.Thread):
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(('127.0.0.1', 1234))
print('Client connected to server')
self.readThread = threading.Thread.__init__(self)
self.writeThread = threading.Thread.__init__(self)
def read(self):
data = self.socket.recv(1024)
if data:
print('Received:', data)
def write(self):
message = input()
self.socket.send(bytes(message, 'utf-8'))
client = Client()
while True:
#do both
答案 0 :(得分:2)
你真的很亲密。尝试这样的事情:
import socket
import threading
class Client(threading.Thread):
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(('127.0.0.1', 1234))
print('Client connected to server')
t = threading.Thread(target = self.read)
t.daemon = True # helpful if you want it to die automatically
t.start()
t2 = threading.thread(target = self.write)
t2.daemon = True
t2.start()
def read(self):
while True:
data = self.socket.recv(1024)
if data:
print('Received:', data)
def write(self):
while True:
message = input()
self.socket.send(bytes(message, 'utf-8'))
client = Client()
值得指出的是,如果你从一个终端读取和写入这种方式,你的提示可能会有点失控。我想,虽然您从打印语句开始,但最终会将数据收集到应用程序中的其他容器中。