@1: 同步网络编程(也就是阻塞方式)
同步网络编程一次只能连接一个客户端。
Server端:
import socket def 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 socket import server def 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不支持分叉; 多线程方式存在同步问题;