python 網路程式設計筆記-socket
阿新 • • 發佈:2019-02-06
python 提供了對底層網路程式設計的socket模組,也提供了諸如urllib、httplib、poplib、ftplib等針對特定功能的程式設計模組。
以下直接貼程式碼測試socket模式使用:
服務端:Server.py
#-*- coding:gbk -*- ''' Created on 2013-4-30 @author: herong ''' import threading from socket import * import time class process(threading.Thread): '''處理類''' __client = None __addr = None def __init__(self,client,addr): threading.Thread.__init__(self) self.__client = client self.__addr = addr print "客戶端%s連線成功!"%(self.__addr[0]) def run(self ): try: while True: recvData = self.__client.recv(gBufferSize) self.__client.send("客戶端%s請求[%s]處理.......\n"%(self.__addr[0],recvData)) print '處理中......' time.sleep(1) print '處理完畢.' self.__client.send("客戶端%s請求[%s]處理完畢!\n"%(self.__addr[0],recvData)) self.__client.send("[end]\n") if recvData == "exit": self.__client.send("伺服器退出!\n") break finally: self.__client.close() class Server(threading.Thread): '''服務端類''' __port = None __socket = None __active = True def __init__(self,port=8001,backlog=10): threading.Thread.__init__(self) self.__port = port self.__socket = socket(AF_INET,SOCK_STREAM) self.__socket.bind(("",self.__port)) self.__socket.listen(backlog) print "服務開啟,開始接收客戶端請求..." def run(self): try: while self.__active: client ,addr = self.__socket.accept() print "client:%s,addr:%s"%(client,addr) p = process(client ,addr) p.setDaemon(True) p.start() finally: self.__socket.close() gBufferSize = 1024 if __name__ == '__main__': Server(8001,5).start()
客戶端:Client.py
#-*- coding:gbk -*- ''' Created on 2013-4-30 @author: herong ''' import threading import sys from socket import * class Client(threading.Thread): '''客戶端類''' __port = None __socket = None __host = None __active = True def __init__(self,host,port=8001): threading.Thread.__init__(self) self.__port = port self.__host = host self.__socket = socket(AF_INET,SOCK_STREAM) self.__socket.connect((self.__host,self.__port)) print "成功連線服務端%s,埠:%s"%(self.__host,self.__port) def run(self): try: while self.__active: cmd = raw_input("請輸入請求服務端指令:") self.__socket.send(cmd) while 1: recvData = self.__socket.recv(gBufferSize) print "服務端返回資訊:%s"%(recvData) if cmd == "exit": sys.exit(0) if '[end]' in recvData: break finally: self.__socket.close() gBufferSize = 1024 if __name__ == '__main__': Client("127.0.0.1",8001).start()
客戶端輸出:
成功連線服務端127.0.0.1,埠:8001
請輸入請求服務端指令:cmd
服務端返回資訊:客戶端127.0.0.1請求[cmd]處理.......
服務端返回資訊:客戶端127.0.0.1請求[cmd]處理完畢!
服務端返回資訊:[end]
請輸入請求服務端指令:
服務端輸出:
服務開啟,開始接收客戶端請求...
client:<socket._socketobject object at 0x0000000002567AD8>,addr:('127.0.0.1', 26097)
客戶端127.0.0.1連線成功!
處理中......
處理完畢.