標籤:
@1: 同步網路編程(也就是阻塞方式)
同步網路編程一次只能串連一個用戶端。
Server端:
import socketdef debugPrint(name, value): print("{0}: {1}".format(name, value))def server(): #1: server = socket.socket() #NOTE: NOT "host = server.gethostname()" host = socket.gethostname() port = 8080 #2: #NOTE: NOT "server.bind(host, port)" TypeError: bind() takes exactly one argument (2 given) server.bind((host, port)) #3: server.listen(3) #listen()的參數為允許等待的串連數 while 1: #4: client, address = server.accept() #accept()會阻塞,直到有用戶端串連 debugPrint("client", client) debugPrint("address", address) #5: client.send("Welcome!") client.close()def main(): server()
Client端:
import socketimport serverdef client(): #1: client = socket.socket() host = socket.gethostname() port = 8080 #2: client.connect((host, port)) #3: content = client.recv(1024) server.debugPrint("From Server", content)def main(): client()
@2: 非同步網路編程(也就是非阻塞方式)
非同步網路編程, 允許多個用戶端連結。
非同步網路編程有3種實現方法: 分叉(多進程), 多線程,非同步IO
分叉方式佔據資源,windows不支援分叉; 多線程方式存在同步問題;
Python Network Programming