1.创建一个文件,文件的第一行写入0,再创建20个任务线程,他们同时打开文件并将文件第一行读出来,加1写回去(将文件原有值覆盖掉)请保证20个任务线程完成后,文件中的第一行一定是20!
2.完成一个cs架构程序,服务端一旦接受到客户端请求文件路径后,判断此文件是否存在,如果存在,将文件内容发送给客户端,如果不存在,也请告知客户端.
```
编程1:
from threading import Thread, Lock
from time import sleep
lock = Lock()
#f1 = open('./a.txt', mode='w')
#f1.write('0')
def thrjob():
try:
lock.acquire()
while True:
f2 = open('./a.txt', mode='r+')
rtext = f2.read(10)
if rtext == '':
# 读到文件结束标志EOF时,返回''
break
print(rtext, type(rtext))
rtext2 = int(rtext)
print(rtext2, type(rtext2))
rtext2 = rtext2 + 1
print(rtext2, type(rtext2))
f3 = open('./a.txt', mode='w')
rtext3 = str(rtext2)
f3.write(rtext3)
finally:
lock.release()
if __name__ == '__main__':
l = []
for i in range(20):
l.append(Thread(target=thrjob))
for i in range(20):
l[i].start()
#for i in range(20):
l[i].join()
print('main will be Gone')
编程2:
服务器端:
import Socket
import os
sd = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
sd.bind(('', 8889))
sd.listen(100)
while True:
try:
# 接听 newsd 数据交换
newsd, raddr = sd.accept()
print("data from ip:{}, port:{}".fORMat(*raddr))
# 收发消息
s = newsd.recv(1024)
s1 = s.decode()
print(s1)
print(os.path.exists(s1))
if os.path.exists(s1):
print('aaaa')
f1 = open(s1, mode='r+', encoding='utf-8')
while True:
rtext = f1.read(10000)
if rtext == '':
# 读到文件结束标志EOF时,返回''
break
print(rtext)
rtext1 = rtext.encode()
newsd.send(rtext1)
else:
s = '未找到'
s1 = s.encode()
newsd.send(s1)
except:
sd.close()
客户端:
import socket
sd = socket.socket()
sd.connect(('192.168.152.1', 8889))
s = './a.txt'
s1 = s.encode()
sd.send(s1)
rtext1 = sd.recv(1024)
rtext = rtext1.decode()
print(rtext)
sd.close()
```
总的来说这几天学的知识用到了io操作,线程,和套接字(socket)和一丢丢的os,将这些东西联系起来,编程1用类去完成会更好些,好多代码框架还是看的老师的样本,尽量自己记下来
下面评论为补充方法
0