1.写一个基于TCP协议套接字,服务端实现接收客户端的连接并发。
#server
import socket
from threading import Thread
import threading
server = socket.socket()
server.bind(
('127.0.0.1',9527)
)
server.listen(3)
def action(conn):
while True:
data = conn.recv(1024)
print(data)
conn.send(data.upper())
if __name__ == '__main__':
while True:
conn,addr = server.accept()
p = threading.Thread(target=action,args = (conn,))
p.start()
#client
import socket
client = socket.socket()
client.connect(
('127.0.0.1',9527)
)
while True:
msg = input('>>: ').strip()
if not msg:
continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print(data)
2.编写一个简单的文本处理工具,具备三个任务,一个接收用户输入,一个将用户输入的内容格式化成大写,一个将格式化后的结果存入文件
from threading import Thread
msgs = []
format = []
def talk():
while True:
msg = input('>>: ').strip()
if not msg:
continue
msgs.append(msg)
def format_msg():
while True:
if msgs:
res = msgs.pop() #列表-删除最后的值
format.append(res.upper())
def save():
while True:
if format:
with open('db.txt','a',encoding='utf-8') as f:
res = format.pop()
f.write(f'{res}
')
if __name__ == '__main__':
t1 = Thread(target=talk)
t2 = Thread(target=format_msg)
t3 = Thread(target=save)
t1.start()
t2.start()
t3.start()