计算机网络自顶向下第二章编程作业

前言

其代码都写了一些注释,就不再解释啥了,直接上代码,我亲自实验了,所以是可以保证运行的

作业1:Web服务器

# import socket module
from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(('', 12000))  # 将TCP欢迎套接字绑定到指定端口
serverSocket.listen(1)  # 最大连接数为1

while True:
    # Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()  # 接收到客户连接请求后,建立新的TCP连接套接字
    try:
        message = connectionSocket.recv(1024)  # 获取客户发送的报文
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read();
        # Send one HTTP header line into socket
        header = ' HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/html\nContent-Length: %d\n\n' %(len(outputdata))
        connectionSocket.send(header.encode())

        # Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())
        connectionSocket.close()
    except IOError:
        # Send response message for file not found
        header = ' HTTP/1.1 404 Found'
        connectionSocket.send(header.encode())

        # Close client socket
        connectionSocket.close()
serverSocket.close()

作业2:UDP ping程序

udpServer.py
# 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))

while True:
	# 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()
	print(message)
	# 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)

udpClient
from socket import*
import time
serverName='127.0.0.1'
serverPort=12000
clientSocket=socket(AF_INET,SOCK_DGRAM)
clientSocket.settimeout(1)
for i in range(10):
    t1=time.time()
    data='ping'+str(i)+str(t1)
    #print('hello world\n')
    clientSocket.sendto(data.encode(), (serverName, serverPort))
    clientSocket.settimeout(1)
    try:
        clientSocket.recv(2048)
        print("RTT:%lf\n"%(time.time()-t1))
    except timeout:
        data='请求超时'
        print(data)
    clientSocket.settimeout(1)
clientSocket.close()

作业3:邮件客户

from socket import *
import base64
msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
#网易接收邮箱服务器为pop3.163.com:123.126.97.79 发送邮箱服务器为 smtp.163.com:123.126.97.4
# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = 'smtp.163.com' #Fill in start   #Fill in end
# Create socket called clientSocket and establish a TCP connection with mailserver
#Fill in start
serverPort=25
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((mailserver,serverPort))
#Fill in end
recv = clientSocket.recv(1024)
print (recv)
data=recv[:3].decode()
if data != '220':
    print ('220 reply not received from server.111')

# Send HELO command and print server response.
heloCommand = 'HELO smtp.163.com\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024)
data1=recv1[:3].decode()
print (recv1)
if data1 != '250':
    print ('250 reply not received from server.')
# Auth 验证
authCommand='AUTH LOGIN\r\n'
clientSocket.send(authCommand.encode())
recv0=clientSocket.recv(1024).decode()
print(recv0)
if recv0[:3]!='334':
    print('334 reply not received from server.111111')

username="******" #填自己的邮箱
password="*******" #需要开启smtp服务,得到其验证码
username = base64.b64encode(username.encode()).decode()
password = base64.b64encode(password.encode()).decode()
clientSocket.send((username+'\r\n').encode())
recv7=clientSocket.recv(1024).decode()
print(recv7)
if recv7[:3]!='334':
    print('334 reply not received from server.2222')

clientSocket.send((password+'\r\n').encode())
recv8=clientSocket.recv(1024).decode()
print(recv8)
if recv8[:3]!='235':
    print('235 reply not received from server.')

# Send MAIL FROM command and print server response.
# Fill in start
mailCommand='MAIL FROM:<******>\r\n'
clientSocket.send(mailCommand.encode())
recv2=clientSocket.recv(1024).decode()
print(recv2)
if recv2[:3]!='250':
    print('250 reply not received from server.234115')
# Fill in end

# Send RCPT TO command and print server response.
# Fill in start
rcptCommand='RCPT TO: <******>\r\n'
clientSocket.send(rcptCommand.encode())
recv3=clientSocket.recv(1024).decode()
print(recv3)
if recv3[:3]!='250':
    print('250 reply not received from server.')
# Fill in end

# Send DATA command and print server response.
# Fill in start
dataCommand='DATA\r\n'
clientSocket.send(dataCommand.encode())
recv4=clientSocket.recv(1024).decode()
print(recv4)
if recv4[:3]!='354':
    print('354 reply not received from server.111')
# Fill in end

# Send message data.
# Fill in start # 这是邮件报文格式
message = 'from:' + "*******" + '\r\n' #从哪个邮箱
message += 'to:' + "********" + '\r\n' # 发到哪个邮箱
message += 'subject:' + "hello world" + '\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.send(endmsg.encode())
recv5=clientSocket.recv(1024).decode()
print(recv5)
if recv5[:3]!='250':
    print('250 reply not received from server.')
# Fill in end

# Send QUIT command and get server response.
# Fill in start
quitCommand='QUIT\r\n'
clientSocket.send(quitCommand.encode())
recv6=clientSocket.recv(1024).decode()
print(recv6)
if recv6[:3]!='221':
    print('221 reply not received from server.')
clientSocket.close()
# Fill in end

作业4:多线程Web代理服务器

from socket import *
# Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
# Fill in start.
tcpSerSock.bind(('0.0.0.0',2333))
tcpSerSock.listen(5)
# Fill in end.
while 1:
    # Strat receiving data from the client
    print('Ready to serve...')
    tcpCliSock, addr = tcpSerSock.accept() #tcpCliSock是服务端对客户端打开的套接字
    print('Received a connection from:', addr)
    message =tcpCliSock.recv(4096).decode()
    print("message:",message)
    # Extract the filename from the given message
    allpath = message.split()[1].partition("//")[2]
    requestWeb = allpath.partition('/')[0]
    filename = allpath.partition("/")[2].replace('/', '_')
    filepath = "E:/data/" + requestWeb + '_' + filename
    print("filename:",filename)
    fileExist =False
    try:
        # Check wether the file exist in the cache 如果在缓存中就直接向客户端发送
        f = open(filepath, "r")
        outputdata = f.readlines()
        fileExist =True
        # ProxyServer finds a cache hit and generates a response message
        # Fill in start.
        for i in range(0,len(outputdata)):
            tcpCliSock.send(outputdata[i].encode())
        # 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 =socket(AF_INET,SOCK_STREAM)
            hostn = requestWeb#得到对象的网址
            print("hostn:",hostn)
            try:
                # Connect to the socket to port 80
                # Fill in start.
                c.connect((hostn,80)) #向服务器发出请求,得到对象并且把对象存到自己缓存也就是文件中,同时作为服务端对客户发出请求
                c.send(message.encode())
                data=c.recv(4096).decode()
                #print("data123:",data)
                #c.send(data.encode())
                tcpCliSock.send(data.encode())
                # 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(filepath, "w")
                tmpFile.write(data)
                tmpFile.close()
                # Fill in start.
                c.close()
                # Fill in end.
            except:
                print("Illegal request")
        else:

            tcpCliSock.close()
tcpSerSock.close()

你可能感兴趣的:(计算机网络,计算机网络)