1. 程式人生 > 實用技巧 >python 多程序模式處理使用者需求

python 多程序模式處理使用者需求

在伺服器端往往需要處理多個使用者需求,這時候就需要建立多個程序

伺服器端程式碼

# 匯入相關包
import multiprocessing,socket
# 全域性變數定義
SERVER_HOST = 'localhost'
SEVER_PORT = 8080
i = 0
# 建立main函式,建立sockert,開啟監聽,建立程序
def main():
    global i
    with socket.socket() as server_socket:
        server_socket.bind((SERVER_HOST,SEVER_PORT))
        server_socket.listen()
        
while True: print("伺服器進入監聽狀態,監聽埠%d" % SEVER_PORT) client_conn,cilent_addr = server_socket.accept() client_process = multiprocessing.Process(target=deal, args=(client_conn, cilent_addr,), name="Process - %d"%i) client_process.start() i = i + 1 #
建立程序指定函式,處理輸入然後輸出,遇到exit退出 def deal(conn, addr): print("客戶端連線地址:{0},連線埠:{1}".format(addr[0],addr[1])) if conn: print("{0}程序連線了。地址:{1}".format(multiprocessing.current_process().name, addr[1])) while True: data = conn.recv(100).decode('UTF-8') if data.upper() == '
BYEBYE': conn.send("exit".encode('UTF-8')) print("%s 程序結束了!!" % multiprocessing.current_process().name) break else: data = "[echo]%s" % data conn.send(data.encode("UTF-8")) if __name__ == '__main__': main()

客戶端程式碼:

import socket
SERVER_HOST = 'localhost'
SERVER_PORT = 8080
def main():
    with socket.socket() as client_socket:
        client_socket.connect((SERVER_HOST,SERVER_PORT))
        print('----連線成功-----')
        while True:
            data = input("請輸入你要的資料:")
            data = client_socket.send(data.encode("UTF-8"))
            data = client_socket.recv(100).decode("UTF-8")
            if data == 'exit':
                print(data)
                break
            else:
                print(data)
        print("該程序結束了")
if __name__ == '__main__':
    main()

成功連線,而且正確返回,當輸入byebye時

程序也成功結束