1.编写一个简单的文本处理工具,具备三个任务,一个接收用户输入,一个将用户输入的内容格式化成大写,一个将格式化后的结果存入文件
from threading import Thread
from multiprocessing import Queue
def recv(q):
cmd = input(">>:").strip()
q.put(cmd)
def large(q):
msg = q.get().upper()
q.put(msg)
def save(q):
new_msg = q.get()
with open("msg.txt","a+",encoding="utf-8") as f:
f.write(new_msg+"\n")
if __name__ == '__main__':
q = Queue()
t1 = Thread(target=recv,args=(q,))
t2 = Thread(target=large,args=(q,))
t3 = Thread(target=save,args=(q,))
t1.start()
t2.start()
t3.start()
2.基于多线程实现并发的套接字通信
服务端
from socket import *
from threading import Thread
def talk(conn):
while True:
try:
data = conn.recv(1024)
if not data:break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
def sever(ip,port):
sever = socket(AF_INET, SOCK_STREAM)
sever.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sever.bind((ip, port))
sever.listen(5)
while True:
conn,addr = sever.accept()
t = Thread(target=talk,args=(conn,))
t.start()
sever.close()
if __name__ == '__main__':
sever("127.0.0.1",8888)
客户端
from socket import *
client = socket(AF_INET,SOCK_STREAM)
client.connect(("127.0.0.1",8888))
while True:
msg = input(">>:").strip()
if not msg:continue
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print(data.decode("utf-8"))