1. 程式人生 > >Python 網路程式設計(一)-基礎知識

Python 網路程式設計(一)-基礎知識

makefile使用:

socket.makefile(mode ='r',buffering = None,*,encoding = None,errors = None,newline = None )

返回一個與套接字相關聯的檔案物件。返回的確切型別取決於給makefile()提供的引數。

這些引數的解釋方式與內建open()函式的解釋方式相同,除了makefile方法唯一支援的mode值是'r'(預設)'w'和'b'。

套接字必須處於阻塞模式; 它可能有超時,但是如果超時發生,檔案物件的內部緩衝區可能會以不一致的狀態結束。

關閉返回的檔案物件makefile()將不會關閉原始套接字,除非所有其他檔案物件已關閉並且 socket.close()已在套接字物件上呼叫。

這段文字的意思是說python的socket模組中提供了makefile()方法,生成一個檔案與socket物件關聯,然後就跟讀普通檔案一樣使用socket。(對普通檔案有open,write等方法)

import socket, sys
port = 70
host = sys.argv[1]
filename = sys.argv[2]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
fd = s.makefile('rw', 0)
fd.write(filename + "\r\n") # 寫入
for line in fd.readlines():
    sys.stdout.write(line)

個人理解:以前需要使用recv()讀取資料,而現在只需要像讀檔案一樣讀取就行了(可能理解有錯,還需進一步瞭解)

例項:

# makefile 
import threading,logging,socket
DATEFMT="%H:%M:%S" #時間格式
FORMAT = "[%(asctime)s]\t [%(threadName)s,%(thread)d] %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT,datefmt=DATEFMT)

sock = socket.socket()
addr = ('127.0.0.1',9999)
event = threading.Event() # 多執行緒

sock.bind(addr)
sock.listen()

def _accept(sock:socket.socket):
    s,addrinfo = sock.accept()
    f = s.makefile(mode='rw')

    while True:
        line = f.readline() # read(10) 文字使用readline
        logging.info(line)

        if line.strip() == 'quit':
            break
        msg = "Your masg = {}. ack".format(line)
        f.write(msg)
        f.flush()
    f.close()
    sock.close()

threading.Tread(target=_accept,args=(sock,)).start()

while not event.wait(2):
    logging.info(sock)