python socket多線程實(shí)現(xiàn)客戶(hù)端與服務(wù)器連接
python socket多線程實(shí)現(xiàn)客戶(hù)端與服務(wù)器連接,供大家參考,具體內(nèi)容如下
之前因?yàn)橐恍┳鳂I(yè)需要完成一個(gè)服務(wù)器監(jiān)聽(tīng)多個(gè)客戶(hù)端的程序,于是就用python寫(xiě)了這樣的程序。話不多說(shuō),直接上代碼。
server代碼:
import json import socket import threading import time import struct class Server(): def __init__(self): self.g_conn_pool = {} # 連接池 # 記錄客戶(hù)端數(shù)量 self.num =0 # 服務(wù)器本地地址 self.address = ('0.0.0.0', 8000) # 初始化服務(wù)器 self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind(self.address) self.server_socket.listen(128) def accept_client(self): """ 接收新連接 """ while True: client_socket, info = self.server_socket.accept() # 阻塞,等待客戶(hù)端連接 print(client_socket,port) # 給每個(gè)客戶(hù)端創(chuàng)建一個(gè)獨(dú)立的線程進(jìn)行管理 thread = threading.Thread(target=self.recv_msg, args=(client_socket,info)) thread.setDaemon(True) thread.start() def recv_msg(self,client,info): # 提示服務(wù)器開(kāi)啟成功 print('服務(wù)器已準(zhǔn)備就緒!') client.sendall("connect server successfully!".encode(encoding='utf8')) # 持續(xù)接受客戶(hù)端連接 while True: try: client.sendall(b'Success') while True: msg = client.recv(1024) msg_recv = msg.decode('utf-8') if not msg_recv:continue else:recv_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print('客戶(hù)端 ' + recv_time + ':\n')print(' ' + msg_recv + '\n') except Exception as e: print('客戶(hù)端斷開(kāi)連接...') exit(-1) break def start_new_thread(self): """啟動(dòng)新線程來(lái)接收信息""" thread = threading.Thread(target=self.accept_client, args=()) thread.setDaemon(True) thread.start()
server服務(wù)器類(lèi),主要是監(jiān)聽(tīng)以及接收客戶(hù)端的信息。
#實(shí)例化一個(gè)Flask節(jié)點(diǎn) app = Flask(__name__) @app.route('/') def hello(): return 'hello' if __name__ == '__main__': #創(chuàng)建解析器 from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-p', '--port', default=5030, type=int, help='port to listen on') args = parser.parse_args() #獲取端口號(hào) port = args.port #實(shí)例化一個(gè)server類(lèi) 并啟動(dòng) py_server = Server() py_server.start_new_thread() #啟動(dòng)Flask節(jié)點(diǎn) app.run(host='127.0.0.1',port=port)
Client代碼
class Client(): def __init__(self): #服務(wù)器ip與端口 self.server_address = ('127.0.0.1', 8000) self.num = 0 def recv_msg(self): print("正在連接服務(wù)器....") # 客戶(hù)端連接服務(wù)器 while True: try: self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #連接服務(wù)器 self.client_socket.connect(self.server_address) num = self.num # 制作報(bào)頭 header_dic = { 'filename': num } header_bytes = json.dumps(header_dic).encode('utf-8') self.client_socket.send(struct.pack('i', len(header_bytes))) self.client_socket.send(header_bytes) #接收信息 while True: msg_recv = self.client_socket.recv(1024).decode('gbk') print(msg_recv) if msg_recv == 'Success':print('客戶(hù)端已與服務(wù)器成功建立連接...') elif not msg_recv:continue else:recv_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print( '服務(wù)器 ' + recv_time + ':\n')print(' ' + msg_recv + '\n') except: print('與服務(wù)器斷開(kāi)連接...') break def start_new_thread(self): """啟動(dòng)新線程來(lái)接收信息""" thread = threading.Thread(target=self.recv_msg, args=()) thread.setDaemon(True) thread.start() def main(): wf = Client() wf.start_new_thread() while True: a = input() wf.client_socket.send(a.encode('utf-8')) if __name__ == '__main__': main()
以上為客戶(hù)端程序的代碼。
下面是運(yùn)行的結(jié)果:
服務(wù)器端:
多個(gè)客戶(hù)端:
代碼實(shí)現(xiàn)還是蠻容易的,具體可以自行修改使用。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。