python并发编程-使用多进程实现socket服务端的并发效果

Client:

import socket

sk = socket.socket()
sk.connect(('127.0.0.1',8080))
msg = sk.recv(1024).decode('utf-8')
print(msg)
msg2 = input('>>>').encode('utf-8')
sk.send(msg2)
sk.close()

Server:

import socket
from multiprocessing import Process
def serve(conn):
    ret = '你好'.encode('utf-8')
    conn.send(ret)
    msg = conn.recv(1024).decode('utf-8')
    print(msg)
    conn.close()

if __name__ == '__main__' :
    sk = socket.socket()
    sk.bind(('127.0.0.1',8080))
    sk.listen()
    try:
        while True:
            conn,addr = sk.accept()
            p = Process(target=serve,args=(conn,))
            p.start()
    finally:
        sk.close()

你可能感兴趣的:(Python)