• day 32 练习


    使用多线程实现socket通信

    可以通过查看服务端输出的 pid 来比较多进程与多线程。

    服务端

    from socket import *
    from threading import Thread
    import os
    
    class Server:
        code = 'utf-8'
        family_net = AF_INET
        type_net = SOCK_STREAM
        request_queue_size = 5
        max_packet_size = 1024
    
        def __init__(self, server_address):
            self.server_address = server_address
            self.socket = socket(self.family_net, self.type_net)
    
            try:
                self.server_bind()
                self.server_listen()
            except:
                self.server_close()
                raise
    
        def server_bind(self):
            self.socket.bind(self.server_address)
    
        def server_listen(self):
            self.socket.listen(self.request_queue_size)
    
        def server_close(self):
            self.socket.close()
    
        def run(self):
            while True:
                print('waiting...')
                self.conn, self.addr = self.socket.accept()
                p = Thread(target=self.sub_p,)
                p.start()
    
        def sub_p(self):
            while True:
                print('多线程 pid:%s'% os.getpid())
                ret = self.conn.recv(self.max_packet_size).decode(self.code)
                if not ret: break
                ret_bytes = ret.upper().encode(self.code)
                self.conn.send(ret_bytes)
    
    
    if __name__ == '__main__':
        s = Server(('127.0.0.1', 8099))
        s.run()

    客户端

    from socket import *
    import os
    
    
    class Client:
        code = 'utf-8'
        family_net = AF_INET
        type_net = SOCK_STREAM
        max_packet_size = 1024
    
        def __init__(self, server_address):
            self.server_address = server_address
            self.socket = socket(self.family_net, self.type_net)
    
            try:
                self.client_connect()
            except:
                self.clent_close()
                raise
    
        def client_connect(self):
            self.socket.connect(self.server_address)
    
        def clent_close(self):
            self.socket.close()
    
        def run(self):
            while 1:
                ret = input('>>>').strip()
                if not ret: break
                self.socket.send(ret.encode(self.code))
                data = self.socket.recv(self.max_packet_size)
                print(data.decode(self.code), os.getpid())
    
    
    if __name__ == '__main__':
        c = Client(('127.0.0.1', 8099))
        c.run()
  • 相关阅读:
    移动网络介绍
    统一导航路由方案
    负载均衡汇总
    Openfire部署和配置说明
    CDN技术介绍
    流媒体
    WebSocket和HTTP的区别与联系
    zabbix 邮件报警
    Linux系统故障-Repair filesystem
    redhat 6.8 配置yum源
  • 原文地址:https://www.cnblogs.com/ysging/p/12331319.html
Copyright © 2020-2023  润新知