Python中實(shí)現(xiàn)socket通信的服務(wù)端比較復(fù)雜,而客戶端非常簡單,所以客戶端基本上都是用sockct模塊實(shí)現(xiàn),而服務(wù)
端用有很多模塊可以使用,如下:
1、客戶端
#!/usr/bin/env python #coding:utf-8 ''' file:client.py date:9/9/17 3:43 PM author:lockey email:lockey@123.com desc:socket編程客戶端,python3.6.2 ''' import socket,sys HOST = '192.168.1.6' PORT = 8998 ADDR =(HOST,PORT) BUFSIZE = 1024 sock = socket.socket() try: sock.connect(ADDR) print('have connected with server') while True: data = input('lockey# ') if len(data)>0: print('send:',data) sock.sendall(data.encode('utf-8')) #不要用send() recv_data = sock.recv(BUFSIZE) print('receive:',recv_data.decode('utf-8')) else: sock.close() break except Exception: print('error') sock.close() sys.exit()
2、SocketServer模塊
為了能夠讓多個(gè)客戶端同時(shí)接入服務(wù)并進(jìn)行通信,服務(wù)端將使用SocketServer模塊來實(shí)現(xiàn),這樣的話用戶不用在子線程結(jié)束后,利用父進(jìn)程對(duì)它進(jìn)行處理,也不用關(guān)心socket的關(guān)閉,一切都由SocketServer來完成。
#!/usr/bin/env python #coding:utf-8 ''' file:client.py date:9/9/17 3:43 PM author:lockey email:lockey@123.com desc:socket編程服務(wù)器端,python3.6.2 ''' from socketserver import BaseRequestHandler,ThreadingTCPServer import threading BUF_SIZE=1024 class Handler(BaseRequestHandler): def handle(self): address,pid = self.client_address print('%s connected!'%address) while True: data = self.request.recv(BUF_SIZE) if len(data)>0: print('receive=',data.decode('utf-8')) cur_thread = threading.current_thread() #response = '{}:{}'.format(cur_thread.ident,data) self.request.sendall('response'.encode('utf-8')) print('send:','response') else: print('close') break if __name__ == '__main__': HOST = '192.168.1.6' PORT = 8998 ADDR = (HOST,PORT) server = ThreadingTCPServer(ADDR,Handler) #參數(shù)為監(jiān)聽地址和已建立連接的處理類 print('listening') server.serve_forever() #監(jiān)聽,建立好TCP連接后,為該連接創(chuàng)建新的socket和線程,并由處理類中的handle方法處理 print(server)
以下測試中我使用另外一臺(tái)主機(jī)和本機(jī)的兩個(gè)中斷去連接服務(wù)器,都可以正常連接并且能進(jìn)行數(shù)據(jù)應(yīng)答交互
注意:此程序示例運(yùn)行平臺(tái)為rhel7.2.x86_64,python版本為3.6.2,對(duì)于windows平臺(tái)和非同一python版本的用戶可能缺乏一定的兼容性,如果是其他平臺(tái)用戶請(qǐng)自行修正?。?/p>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com