计算机网络:自顶向下方法读书笔记(五)
程序员文章站
2024-02-21 23:25:04
...
编程练习1:Web服务器
from socket import *
import sys # 系统库
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', 8088))
serverSocket.listen(1)
print('The server is ready to receive')
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024).decode()
filename = message.split()[1]
# 打开服务器所在目录下的对应文件
f = open(filename[1:])
outputdata = f.read()
# Send one HTTP header line into socket
# 必须写状态行,否则浏览器无法响应
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())
# Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
# Send response message for file not found
# 如果返回这个状态码,则页面会根据404状态码显示页面
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())
# 如果按下面的内容返回,则请求成功页面,页面写着404 NOT Found
# connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())
# connectionSocket.send("404 Not Found".encode())
# Close client socket
connectionSocket.close()
serverSocket.close()
sys.exit() #结束进程用
编程练习2:UDP ping 程序
- server
# 随机库
import random
from socket import *
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', 12000))
while True:
rand = random.randint(0, 10)
message, address = serverSocket.recvfrom(1024)
modifiedMessage = message.upper()
if rand < 4:
continue
serverSocket.sendto(modifiedMessage, address)
- client
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):
start = time.time()
try:
clientSocket.sendto('message'.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(1024)
end = time.time()
print('Ping', i, end - start)
except:
print('Request timed out')
clientSocket.close()
编程练习3:邮件客户
from socket import *
title = "Subject: Hello!"
msg = "\n\n I love computer networks!"
endmsg = "\r\n.\r\n"
mailserver = 'smtp.163.com' # Fill in start #Fill in end
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.')
# 向服务器标识用户身份
heloCommand = 'HELO smtp.163.com\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024).decode()
print(recv1)
if recv1[:3] != '250':
print('250 reply not received from server.')
# 登录指令
loginCommand = 'AUTH LOGIN\r\n'
clientSocket.send(loginCommand.encode())
recv2 = clientSocket.recv(1024).decode()
print(recv2)
# 输入登录名和密码,需要使用base64编码
clientSocket.send('xxx\r\n'.encode())
recv3 = clientSocket.recv(1024).decode()
print(recv3)
clientSocket.send('xxx\r\n'.encode())
recv4 = clientSocket.recv(1024).decode()
print(recv4)
# 发送者邮箱
mailCommand = 'MAIL FROM: <[email protected]>\r\n'
clientSocket.send(mailCommand.encode())
recv5 = clientSocket.recv(1024).decode()
print(recv5)
if recv5[:3] != '250':
print('250 reply not received from server.')
# 接收者邮箱
rcptCommand = 'RCPT TO: <[email protected]>\r\n'
clientSocket.send(rcptCommand.encode())
recv6 = clientSocket.recv(1024).decode()
print(recv6)
if recv6[:3] != '250':
print('250 reply not received from server.')
# 输入信息指令
clientSocket.send(('DATA\r\n').encode())
recv7 = clientSocket.recv(1024).decode()
print(recv7)
# 输入信息内容并结束、发送(注意会被当做垃圾邮件处理,我这里测试只是自己发给自己)
clientSocket.send((title+msg+endmsg).encode())
recv8 = clientSocket.recv(1024).decode()
print(recv8)
if recv8[:3] != '250':
print('250 reply not received from server.')
# 结束指令
clientSocket.send('QUIT\r\n'.encode())
recv9 = clientSocket.recv(1024).decode()
print(recv9)
编程练习4:多线程web代理服务器
from socket import *
import sys
if len(sys.argv) <= 1:
print('Usage : "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address Of Proxy Server]')
sys.exit(2)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind((sys.argv[1], 8080))
tcpSerSock.listen(10)
while 1:
print('Ready to serve...')
tcpCliSock, addr = tcpSerSock.accept()
print('Received a connection from:', addr)
message = tcpCliSock.recv(4096)
print(message)
print(message.split()[1])
filename = message.split()[1].partition('/'.encode())[2]
print(filename)
fileExist = "false"
filetouse = "/" + filename.decode()
print(filetouse)
try:
f = open(filetouse[1:], "r")
outputdata = f.read()
fileExist = "true"
tcpCliSock.send("HTTP/1.1 200 OK\r\n".encode())
tcpCliSock.send("Content-Type:text/html\r\n".encode())
for i in range(0, len(outputdata)):
tcpCliSock.send(outputdata[i].encode())
tcpCliSock.send("\r\n".encode())
tcpCliSock.close()
print('Read from cache')e
except IOError:
if fileExist == "false":
c = socket(AF_INET, SOCK_STREAM)
hostn = filename.replace("www.".encode(), "".encode(), 1)
print(hostn)
try:
hostnaddr = gethostbyname(hostn.decode())
print(hostnaddr)
c.connect((hostnaddr, 80))
c.send(("GET /" + " HTTP/1.1\r\n" + "Host:" + filename.decode() + "\r\n\r\n").encode())
response = c.recv(4096)
tmpFile = open("./" + filename.decode(), "wb")
tmpFile.write(response)
tmpFile.close()
except:
print(error)
print("Illegal request")
else:
tcpCliSock.send("HTTP/1.1 200 OK\r\n".encode())
tcpCliSock.send("404 Not Found".encode())
tcpCliSock.close()