# 作业
* 整理并发编程三天内容理论,用自己的概述
* 需要掌握如何开设进程和如何开设线程的代码
* 利用多进程或多线程自己实现TCP服务端的并发
* 整理python基础阶段知识点及项目代码,ATM购物车,选课系统一定要自己脱稿从头到位敲出来
* 预习并发编程剩余知识点,参考博客小猿取经
TCP服务端实现并发的效果
1、用多进程实现:
#多进程 from multiprocessing import Process import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(("127.0.0.1",9000)) phone.listen(5) #通信循环函数 def talk(conn,client_addr): while True: try: msg=conn.recv(1024) if not msg:break conn.send(msg.upper()) except Exception: break if __name__ == '__main__': while True: conn,client_addr=phone.accept() p=Process(target=talk,args=(conn,client_addr)) p.start() server
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8080)) while True: msg=input('>>: ').strip() if not msg:continue client.send(msg.encode('utf-8')) msg=client.recv(1024) print(msg.decode('utf-8')) client
2、多线程实现
from threading import Thread import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(("127.0.0.1",9000)) phone.listen(5) #通信循环函数 def talk(conn,client_addr): while True: try: msg=conn.recv(1024) if not msg:break conn.send(msg.upper()) except Exception: break if __name__ == '__main__': while True: #多线程 conn, client_addr = phone.accept() t=Thread(target=talk,args=(conn,client_addr)) t.start() server
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',9000)) while True: msg=input('>>: ').strip() if not msg:continue client.send(msg.encode('utf-8')) msg=client.recv(1024) print(msg.decode('utf-8')) client