Python3之socket实现并发

服务端

import socket
from multiprocessing import Process

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1', 8080))
s.listen(5)


class Communicate(Process):
    def __init__(self, conn):
        super().__init__()
        self.conn = conn

    def run(self):
        while 1:
            try:

                data = self.conn.recv(1024)
                if not data: break
                self.conn.send(data.upper())
            except Exception:
                break
        self.conn.close()
#
# def communicate(conn, addr):
#     while 1:
#         try:
#
#             data = conn.recv(1024)
#             if not data: break
#             conn.send(data.upper())
#         except Exception:
#             break
#     conn.close()


if __name__ == '__main__':

    while 1:
        conn, addr = s.accept()
        # p = Process(target=communicate, args=(conn, addr))
        # p.start()
        p = Communicate(conn)
        p.start()

    s.close()

客户端

import socket

c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect(('127.0.0.1',8080))

while 1:
    msg = input('>>:').strip()
    if not msg:continue
    c.send(msg.encode('utf-8'))
    data = c.recv(1024)
    print(data.decode('utf-8'))
c.close()

你可能感兴趣的:(Python)