作业1:Web服务器

# WebServer.py# import socket module
from concurrent.futures import thread
from socket import *
import sys # In order to terminate the program
import threadingdef webProcess(connectionSocket):try: message = connectionSocket.recv(1024).decode() print(message)filename = message.split()[1]                  f = open(filename[1:], encoding='utf-8')                         outputdata = f.read()             #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 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 ErrorMessage = "HTTP/1.1 404 Not Found\r\n\r\n"connectionSocket.send(ErrorMessage.encode())#Close client socket connectionSocket.close()serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverPort = 6789
serverSocket.bind(('', serverPort))
serverSocket.listen(1)while True: #Establish the connection print('Ready to serve...') connectionSocket, addr = serverSocket.accept()          thread = threading.Thread(target=webProcess, args=(connectionSocket, ))thread.start()serverSocket.close()
sys.exit() #Terminate the program after sending the corresponding data
# WebClient.py#import socket module
from socket import *
import sys # In order to terminate the program clientSocket = socket(AF_INET, SOCK_STREAM)
ServerPort = 6789
ServerName = '127.0.0.1'
clientSocket.connect((ServerName, ServerPort))while True: Head = """GET /HelloWorld.html HTTP/1.1\r\nHost: %s:%s\r\nConnection: close\r\nUser-agent: Mozilla/5.0\r\nAccept-language: en""" % (ServerName, ServerPort)clientSocket.send(Head.encode('utf-8'))data = clientSocket.recv(1024)print(data)with open('response.html', 'ab+') as f:f.write(data)

作业2:UDP ping程序

# UDPPingerClient.py# UDPPingerServer.py
# We will need the following module to generate randomized lost packets
from email import message
import random
from socket import *
import timeserverName = '127.0.0.1'
serverPort = 12000
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
ClientSocket = socket(AF_INET, SOCK_DGRAM)
ClientSocket.settimeout(1)RTTList = []
RTTMin = float(1)
RTTMax = float(0)for i in range(10):# Generate random number in the range of 0 to 10 rand = random.randint(0, 10)     # If rand is less is than 4, we consider the packet lost and do not respond if rand < 4: continue # Otherwise, the server responds     try:oldTime = time.time()sendTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(oldTime))message = 'package %d, client local time:%s' % (i + 1, sendTime)ClientSocket.sendto(message.encode(), (serverName, serverPort))modifiedMessage, serverAddress = ClientSocket.recvfrom(1024)rtt = time.time() - oldTimeRTTList.append(rtt)RTTMax = max(rtt, RTTMax)RTTMin = min(rtt, RTTMin)print("Ping %d %s RTT:%f" % (i + 1, modifiedMessage.decode(), rtt))except Exception as e:print('Request timed out')print("\n>> Summary: RTT Min: %f, RTT Max %f, RTT Mean: %f" % (RTTMin, RTTMax, sum(RTTList) / len(RTTList)))

作业3:邮件客户

from pydoc import cli
from socket import *
import base64subject = "I love computer networks!"
contenttype = "text/plain"
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" #Fill in start   #Fill in end
# Create socket called clientSocket and establish a TCP connection with mailserver #Fill in start   fromAddress = '******@163.com'
toAddress = '******@qq.com'username = base64.b64encode(fromAddress.encode()).decode()
passwd = base64.b64encode('******'.encode()).decode()clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((mailserver, 25))#Fill in end
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.') # Auth
clientSocket.send('AUTH LOGIN\r\n'.encode())
recv = clientSocket.recv(1024).decode()
print(recv)
if recv[:3] != '334':print('334 reply not received from server.') clientSocket.send((username + '\r\n').encode())
recv = clientSocket.recv(1024).decode()
print(recv)
if recv[:3] != '334':print('334 reply not received from server.') clientSocket.send((passwd + '\r\n').encode())
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
MailFromCommand = 'MAIL FROM: <' + fromAddress + '>\r\n'
clientSocket.sendall(MailFromCommand.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
RcptTo = 'RCPT TO: <' + toAddress + '>\r\n'
clientSocket.sendall(RcptTo.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
Data = 'DATA\r\n'
clientSocket.send(Data.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 += 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
QuitMsg = 'QUIT'
clientSocket.send(QuitMsg.encode())clientSocket.close()
# Fill in end

作业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) # Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
# Fill in start.
tcpSerPort = 8899
tcpSerSock.bind(('', tcpSerPort))
tcpSerSock.listen(5)
# Fill in end. while True: # Strat receiving data from the client print('Ready to serve...') tcpCliSock, addr = tcpSerSock.accept() print('Received a connection from:', addr) message = tcpCliSock.recv(4096).decode() # 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" print('File Exists!')# 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. 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 print('Creating socket on proxyserver')c = socket(AF_INET, SOCK_STREAM) # Fill in start.   # Fill in end. hostn = filename.replace("www.","",1)          print(hostn)                                   try: # Connect to the socket to port 80 # Fill in start.   c.connect((hostn, 80))print('Socket connected to port 80 if the host')c.sendall(message.encode())# 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.   buff = c.recv(4096)tcpCliSock.sendall(buff)# 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.   tmpFile.writelines(buff.decode().replace('\r\n', '\n'))tmpFile.close()# Fill in end.    except: print("Illegal request")                                                else: # HTTP response message for file not found # Fill in start.   print('File Not Found...Stupid Andy')# Fill in end. # Close the client and the server sockets     tcpCliSock.close()
# Fill in start.
tcpSerSock.close()
# Fill in end.

计算机网络自顶向下-套接字编程作业相关推荐

  1. 计算机网络自顶向下方法套接字编程作业

    本博客是针对,<计算机网络自顶向下方法>一书第二章后面套接字编程作业, 所有代码均已上传至我的github:https://github.com/inspurer/ComputerNetw ...

  2. 计算机网络自顶向下方法 第二章套接字编程作业 邮件客户 答案

    https://github.com/jzplp/Computer-Network-A-Top-Down-Approach-Answer 作业3: 邮件客户 官方文档 文档翻译 编程作业答案 #改为P ...

  3. 《计算机网络:自顶向下方法(原书第6版)》一2.7 TCP套接字编程

    本节书摘来华章计算机<计算机网络:自顶向下方法(原书第6版)>一书中的第2章 ,第2.7节,(美)James F.Kurose Keith W.Ross 著 陈 鸣 译 更多章节内容可以访 ...

  4. 「计算机网络:自顶向下方法阅读笔记」套接字编程:生成网络应用

    <计算机网络:自顶向下方法>阅读笔记系列 学习套接字编程就是探讨一下网络应用程序是如何实际编写的. 先回顾一下套接字:网络应用是由一对程序(客户程序和服务器程序)组成,位于两个不同的端系统 ...

  5. 计算机网络实验4 - TCP套接字编程 - 点对点聊天 - 代码实现

    客户端 package chat;import java.io.IOException; import java.io.PrintStream; import java.net.Socket; imp ...

  6. 计算机网络实验:UDP套接字编程

    计算机网络实验:UDP套接字编程 一.安装实验环境 二.编写程序并调试程序 三.实验代码 一.安装实验环境 这次实验使用的是C/C++来编写套接字程序,可以安装DEVC++.VC6.0.CodeBlo ...

  7. 计算机网络详解--套接字编程

    目录 1.什么是网络编程 2.TCP/IP协议 3.Socket套接字 流套接字:使用传输层TCP(传输控制协议) 数据报套接字:使用传输层UDP(用户数据报协议) 原始套接字 4.Java数据报套接 ...

  8. 计算机网络(二) | 网络编程基础、Socket套接字、UDP和TCP套接字编程

    目录 一.网络编程基础 1.1 为什么需要网络编程 1.2 什么是网络编程 1.3 网络编程中的基本概念 二.Socket套接字 2.1 概念 2.2 分类 2.3 Java数据报套接字通信模型 2. ...

  9. 计算机网络实验二:UDP套接字编程实现多人聊天

    一.实验目的 1. 实现一个能够在局域网中进行点对点聊天的实用程序. 2. 熟悉c++.Java等高级编程语言网络编程的基本操作. 3. 基本了解对话框应用程序的编写过程. 4. 实现UDP套接字编程 ...

最新文章

  1. MOSS 2010:Visual Studio 2010开发体验(14)——列表开发之事件接收器
  2. 万字长文,解读“幕后产品”的核心观点
  3. php之Deprecated 问题
  4. 当下最实用计算机编程语言,目前最流行的计算机编程语言是什么?
  5. 《图解深度学习》学习笔记(一)
  6. STM32F429+W25Q256+TouchFGX
  7. 多个html5页面背景音乐,HTML5页面背景音乐代码 网页背景音乐通用代码
  8. 刻意玩具教具化没用,童心制物如何让孩子真正玩出名堂
  9. 2 电感耦合方式的射频前端
  10. HTML常用语法及标签(第一天所学)
  11. 程序员必上的20大网站
  12. 微信开发高级群发接口
  13. 射灯安装方法图解_射灯安装图解
  14. 英语谚语精选(English Proverb Collection)
  15. 求圆和直线之间的交点
  16. 如何进行SEO站内优化,让你的网站更易被搜索引擎收录
  17. android系统APK签名生成大全
  18. 如何将usb设置设为第一启动项
  19. GitHub 开源的超简单头像生成器,网友:好Q啊
  20. PEP8中文翻译(转)

热门文章

  1. 同步和异步Socket多线程编程基本模型介绍
  2. 武林外传之勇夺金掌柜 【安卓游戏】
  3. excle统计不同的内容的单元格个数
  4. flyme禁止系统更新_魅族怎么关闭系统更新
  5. LintCode 138.子数组之和
  6. 锂矿的这个逻辑,我自己都不敢相信了
  7. 【Vue3】第十四部分 父子组件传参
  8. sql 查找一个月内数据
  9. 建筑施工技术【22】
  10. js中出现错误:Uncaught TypeError: date.getDay is not a function