P2P应用
相比于客户-服务器体系结构,P2P具有自扩展性,表现在对等方N越大,最小分发时间也趋于平缓。这种自扩展性的直接成因是:对等方除了是比特的消费者外还是它们的重新分发者。
有两种典型因特网应用十分适合P2P体系结构,一种是文件分发,另一种是大型对等方社区中的数据库;P2P体系结构有着良好的自扩展性;
BitTorrent 是一种用于文件分发的流行P2P协议;用BitTorrent的术语来说,参与一个特定文件分发的所有对等方的集合被称为一个洪流;在一个洪流中的对等方彼此下载等长度的文件块;当一个对等方下载文件块的时候,也向其他对等方发送了多个块;一旦某对等方获得了完整文件,就可以自私地离开洪流或者大公无私地留下来继续向其他对等方发送文件;
套接字编程
UDP套接字编程:
功能:客户从键盘读入一行字符,发给服务端,服务端将其转成大写返回给客户端
UDPClient.py
from socket import *
serverName = "127.0.0.1"
serverPort = 10021
clientSocket = socket(AF_INET,SOCK_DGRAM)
while True:
message = raw_input('Input lowercase sentence:')
if message=='quit':
break
clientSocket.sendto(message,(serverName,serverPort))
modifiedMessage,serverAddress = clientSocket.recvfrom(2048)
print modifiedMessage
clientSocket.close()
AF_INET表示底层为IPv4,SOCK_DGRAM表示其为UDP套接字
UDPServer.py
from socket import *
serverName = "127.0.0.1"
serverPort = 10021
serverSocket = socket(AF_INET,SOCK_DGRAM)
serverSocket.bind((serverName,serverPort))
print ("The server is ready to receive")
while True:
message,clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage,clientAddress)
TCP套接字编程:
TCPClient.py
from socket import *
serverName = "127.0.0.1"
serverPort = 10021
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
while True:
message = raw_input('Input lowercase sentence:')
if message=='quit':
break
clientSocket.send(message)
modifiedMessage,serverAddress = clientSocket.recvfrom(2048)
print modifiedMessage
clientSocket.close()
TCPServer.py
from socket import *
serverName = "127.0.0.1"
serverPort = 10021
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((serverName,serverPort))
serverSocket.listen(1)
print ("The server is ready to receive")
while True:
connectionSocket,addr = serverSocket.accept()
message = connectionSocket.recv(2048)
modifiedMessage = message.upper()
connectionSocket.send(modifiedMessage)
connectionSocket.close()