zoukankan      html  css  js  c++  java
  • python每日作业 4/24

    # 作业

    * 整理并发编程三天内容理论,用自己的概述
    * 需要掌握如何开设进程和如何开设线程的代码
    * 利用多进程或多线程自己实现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
    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
    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
    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
    client
  • 相关阅读:
    从xib初始化的UIView如何继承?
    no implicit conversion of nil into String
    @synchronized(self) 加锁引起的Crash
    iOS手工Crash解析
    iOS线程While-True死循环会发生什么
    2019年新年总结
    218. The Skyline Problem-Hard
    ReplayKit 启动录制按钮 RPSystemBroadcastPickerView 的使用
    S212-搜索+字典树-212. Word Search II-(Hard)
    mybatis批量生成
  • 原文地址:https://www.cnblogs.com/baicai37/p/12769444.html
Copyright © 2011-2022 走看看