#import socket module from socket import * serverSocket = socket(AF_INET, SOCK_STREAM) #Prepare a sever socket #Fill in start #Fill in end whileTrue: #Establish the connection print'Ready to serve...'# python2的语法 connectionSocket, addr = #Fill in start #Fill in end try: message = #Fill in start #Fill in end filename = message.split()[1] f = open(filename[1:]) outputdata = #Fill in start #Fill in end #Send one HTTP header line into socket #Fill in start #Fill in end
#Send the content of the requested file to the client for i inrange(0, len(outputdata)): connectionSocket.send(outputdata[i]) connectionSocket.close() except IOError: #Send response message for file not found #Fill in start #Fill in end
#Close client socket #Fill in start #Fill in end serverSocket.close()
需要在标有#Fill in start 和 # Fill in end的地方填写代码。另外,每个地方都可能需要不止一行代码。
#import socket module from socket import * serverSocket = socket(AF_INET, SOCK_STREAM) #Prepare a sever socket #Fill in start HOST = '127.0.0.1'# gethostname() PORT = 6789 serverSocket.bind((HOST,PORT)) # 绑定主机,端口到套接字 serverSocket.listen(5) # 开始TCP监听,最大连接数至少为1 #Fill in end whileTrue: #Establish the connection print ('Ready to serve...') # 修改python2的语法 connectionSocket, addr = serverSocket.accept() # 被动接收TCP客户端连接 try: message = connectionSocket.recv(1024) # 接收 客户发送的TCP报文数据 filename = message.split()[1] f = open(filename[1:]) outputdata = f.read() f.close() #Fill in start #Fill in end #Send one HTTP header line into socket header = 'HTTP/1.1 200 OK\r\n\r\n' connectionSocket.send(header.encode())
#Send the content of the requested file to the client for i inrange(0, len(outputdata)): connectionSocket.send(outputdata[i].encode()) connectionSocket.close() except IOError: #Send response message for file not found #Fill in start header = 'HTTP/1.1 404 Not Found\r\n\r\n' connectionSocket.send(header.encode()) #Fill in end
#Close client socket #Fill in start connectionSocket.close() #Fill in end serverSocket.close()
# UDPPingerServer.py # We will need the following module to generate randomized lost packets import random from socket import * import random
# Create a UDP socket # Notice the use of SOCK_DGRAM for UDP packets serverSocket = socket(AF_INET, SOCK_DGRAM) # Assign IP address and port number to socket serverSocket.bind(('', 12000))
whileTrue: # Generate random number in the range of 0 to 10 rand = random.randint(0, 10) # Receive the client packet along with the address it is coming from message, address = serverSocket.recvfrom(1024) # Capitalize the message from the client message = message.upper() # If rand is less is than 4, we consider the packet lost and do not respond if rand < 4: continue # Otherwise, the server responds serverSocket.sendto(message, address)
for i inrange(10): sendTime = time.time() message = ('Ping %d %s' % (i + 1, sendTime)).encode() try: clientSocket.sendto(message,(HOST,PORT)) # 将信息发送到服务器 modifiedMessage, serverAddress = clientSocket.recvfrom(1024) # 从服务器接收信息,同时也能得到服务器地址 rtt = time.time() - sendTime print('Sequence %d : Request from %s , RTT = %.3f' % (i+1,HOST,rtt)) except Exception as e: print('Sequence %d : Request from %s time out!' % (i+1,HOST)) clientSocket.close()
测试结果:
1 2 3 4 5 6 7 8 9 10
Sequence 1 : Request from 127.0.0.1 time out! Sequence 2 : Request from 127.0.0.1 time out! Sequence 3 : Request from 127.0.0.1 time out! Sequence 4 : Request from 127.0.0.1 time out! Sequence 5 : Request from 127.0.0.1 , RTT = 0.000 s Sequence 6 : Request from 127.0.0.1 , RTT = 0.000 s Sequence 7 : Request from 127.0.0.1 time out! Sequence 8 : Request from 127.0.0.1 , RTT = 0.000 s Sequence 9 : Request from 127.0.0.1 , RTT = 0.000 s Sequence 10 : Request from 127.0.0.1 , RTT = 0.000 s
from socket import * msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailserver mailserver = #Fill in start #Fill in end # Create socket called clientSocket and establish a TCP connection with mailserver #Fill in start
#Fill in end recv = clientSocket.recv(1024) print recv if recv[:3] != '220': print'220 reply not received from server.'
# Send HELO command and print server response. heloCommand = 'HELO Alice\r\n' clientSocket.send(heloCommand) recv1 = clientSocket.recv(1024) print recv1 if recv1[:3] != '250': print'250 reply not received from server.'
# Send MAIL FROM command and print server response. # Fill in start
# Fill in end
# Send RCPT TO command and print server response. # Fill in start
# Fill in end
# Send DATA command and print server response. # Fill in start
# Fill in end
# Send message data. # Fill in start
# Fill in end
# Message ends with a single period. # Fill in start
# Fill in end
# Send QUIT command and get server response. # Fill in start
msg = "\r\n I love computer networks!"# 邮件内容 endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailserver mailserver = 'smtp.163.com'
subject = "I love computer networks!"# 邮件标题 contenttype = "text/plain"
# Sender and reciever fromaddress = "xxx@163.com" toaddress = "xxx@qq.com"
# Auth information (Encode with base64) base64加密处理用户名和密码 username = base64.b64encode("xxx@163.com".encode()) + b'\r\n' password = base64.b64encode("xxx".encode()) + b'\r\n'
# Create socket called clientSocket and establish a TCP connection with mailserver clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((mailserver, 25))
recv = clientSocket.recv(1024).decode() print(recv) if recv[:3] != '220': print('220 reply not received from server.')
# Send HELO command and print server response. heloCommand = 'HELO Alice\r\n' clientSocket.send(heloCommand.encode()) recv1 = clientSocket.recv(1024).decode() print(recv1) if recv1[:3] != '250': print('250 reply not received from server.')
# 登陆邮箱过程 clientSocket.sendall('AUTH LOGIN\r\n'.encode()) recv = clientSocket.recv(1024).decode() print(recv) if (recv[:3] != '334'): print('334 reply not received from server')
clientSocket.sendall(username) recv = clientSocket.recv(1024).decode() print(recv) if (recv[:3] != '334'): print('334 reply not received from server')
clientSocket.sendall(password) recv = clientSocket.recv(1024).decode() print(recv) if (recv[:3] != '235'): print('235 reply not received from server')
# Send MAIL FROM command and print server response. # Fill in start clientSocket.sendall(('MAIL FROM: <' + fromaddress + '>\r\n').encode()) recv = clientSocket.recv(1024).decode() print(recv) if (recv[:3] != '250'): print('250 reply not received from server') # Fill in end
# Send RCPT TO command and print server response. # Fill in start clientSocket.sendall(('RCPT TO: <' + toaddress + '>\r\n').encode()) recv = clientSocket.recv(1024).decode() print(recv) if (recv[:3] != '250'): print('250 reply not received from server') # Fill in end
# Send DATA command and print server response. # Fill in start clientSocket.send('DATA\r\n'.encode()) recv = clientSocket.recv(1024).decode() print(recv) if (recv[:3] != '354'): print('354 reply not received from server') # Fill in end
# Send message data. # Fill in start message = 'from:' + fromaddress + '\r\n' message += 'to:' + toaddress + '\r\n' message += 'subject:' + subject + '\r\n' message += 'Content-Type:' + contenttype + '\t\n' message += '\r\n' + msg clientSocket.sendall(message.encode()) # Fill in end
# Message ends with a single period. # Fill in start clientSocket.sendall(endmsg.encode()) recv = clientSocket.recv(1024).decode() print(recv) if (recv[:3] != '250'): print('250 reply not received from server') # Fill in end
# Send QUIT command and get server response. # Fill in start clientSocket.sendall('QUIT\r\n'.encode()) # Fill in end
iflen(sys.argv) <= 1: print'Usage : "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address Of Proxy Server' sys.exit(2) # Create a server socket, bind it to a port and start listening tcpSerSock = socket(AF_INET, SOCK_STREAM) # Fill in start. # Fill in end. while1: # Strat receiving data from the client print'Ready to serve...' tcpCliSock, addr = tcpSerSock.accept() print'Received a connection from:', addr message = # Fill in start. # Fill in end. print message # Extract the filename from the given message print message.split()[1] filename = message.split()[1].partition("/")[2] print filename fileExist = "false" filetouse = "/" + filename print filetouse try: # Check wether the file exist in the cache f = open(filetouse[1:], "r") outputdata = f.readlines() fileExist = "true" # ProxyServer finds a cache hit and generates a response message tcpCliSock.send("HTTP/1.0 200 OK\r\n") tcpCliSock.send("Content-Type:text/html\r\n") # Fill in start. # Fill in end. print'Read from cache' # Error handling for file not found in cache except IOError: if fileExist == "false": # Create a socket on the proxyserver c = # Fill in start. # Fill in end. hostn = filename.replace("www.","",1) print hostn try: # Connect to the socket to port 80 # Fill in start. # Fill in end. # Create a temporary file on this socket and ask port 80 for the file requested by the client fileobj = c.makefile('r', 0) fileobj.write("GET "+"http://" + filename + " HTTP/1.0\n\n") # Read the response into buffer # Fill in start. # Fill in end. # Create a new file in the cache for the requested file. # Also send the response in the buffer to client socket and the corresponding file in the cache tmpFile = open("./" + filename,"wb") # Fill in start. # Fill in end. except: print"Illegal request" else: # HTTP response message for file not found # Fill in start. # Fill in end. # Close the client and the server sockets tcpCliSock.close() # Fill in start. # Fill in end.