博客
关于我
socket实现简单的Web服务器
阅读量:395 次
发布时间:2019-03-05

本文共 2805 字,大约阅读时间需要 9 分钟。

Web服务器实现

代码注解版本

from socket import *import sys# 创建TCP套接字,使用IPv4协议,类型为TCPserverSocket = socket(AF_INET, SOCK_STREAM)# 指派服务器地址和端口serverPort = 6789serverSocket.bind(("", serverPort))# 设置监听,最大连接数为1serverSocket.listen(1)while True:    print('The server is ready to receive')    # 等待客户端连接,返回新的连接套接字和地址    connectionSocket, addr = serverSocket.accept()    try:        # 接收客户端的HTTP请求,最大接收1024字节        message = connectionSocket.recv(1024).decode()        # 提取URL中的路径,假设格式为“/filename.html”        filename = message.split()[1]                # 打开对应的文件        # [1:]用于去掉前导斜杠,避免错误        try:            f = open(filename[1:])            # 读取文件内容            outputdata = f.read()            # 发送HTTP响应头            connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())            # 发送文件内容            for i in range(0, len(outputdata)):                connectionSocket.send(outputdata[i].encode())            # 发送结束标记            connectionSocket.send("\r\n".encode())        except IOError:            # 文件不存在,返回404 Not Found            connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())            connectionSocket.send("

404 Not Found

\r\n".encode()) except Exception as e: # 处理其他错误,例如连接中断 print(f"Error: {e}") finally: # 关闭客户端连接 connectionSocket.close() # 关闭服务器套接字 serverSocket.close() # 退出程序 sys.exit()

简洁版本

from socket import *import sys# 创建TCP套接字,使用IPv4协议,类型为TCPserverSocket = socket(AF_INET, SOCK_STREAM)# 指派服务器地址和端口serverPort = 6789serverSocket.bind(("", serverPort))# 设置监听,最大连接数为1serverSocket.listen(1)while True:    print('The server is ready to receive')    # 等待客户端连接,返回新的连接套接字和地址    connectionSocket, addr = serverSocket.accept()    try:        # 接收客户端的HTTP请求        message = connectionSocket.recv(1024).decode()        # 提取文件名        filename = message.split()[1][1:]        # 打开文件        try:            f = open(filename, 'r')            # 读取文件内容            outputdata = f.read()            # 发送HTTP响应头            connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())            # 发送文件内容            connectionSocket.send(outputdata.encode())            # 发送结束标记            connectionSocket.send("\r\n".encode())        except IOError:            # 文件不存在,返回404            connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())            connectionSocket.send("

404 Not Found

\r\n".encode()) except Exception as e: print(f"Error: {e}") finally: connectionSocket.close() serverSocket.close() sys.exit()

测试说明

  • 服务器端

    • WebServer.pyHelloWorld.html 放在同一目录下。
    • 在终端运行:python WebServer.py
    • 服务器将在端口6789监听。
  • 客户端

    • 打开浏览器,访问 http://localhost:6789/HelloWorld.html
    • 浏览器显示“Hello world!”。
  • 测试404错误

    • 在地址栏输入 http://localhost:6789/abc.html
    • 应收到404 Not Found页面。
  • 确保服务器和客户端在同一局域网内,或者修改服务器IP地址以供外部访问。

    转载地址:http://jzhwz.baihongyu.com/

    你可能感兴趣的文章
    Objective-C 编码规范
    查看>>
    Objective-Cfor循环实现Factorial阶乘算法 (附完整源码)
    查看>>
    Objective-C——判断对象等同性
    查看>>
    objective-c中的内存管理
    查看>>
    Objective-C之成魔之路【7-类、对象和方法】
    查看>>
    Objective-C享元模式(Flyweight)
    查看>>
    Objective-C以递归的方式实现二叉搜索树算法(附完整源码)
    查看>>
    Objective-C内存管理教程和原理剖析(三)
    查看>>
    Objective-C实现 Greedy Best First Search最佳优先搜索算法(附完整源码)
    查看>>
    Objective-C实现 jugglerSequence杂耍者序列算法 (附完整源码)
    查看>>
    Objective-C实现 lattice path格子路径算法(附完整源码)
    查看>>
    Objective-C实现1000 位斐波那契数算法(附完整源码)
    查看>>
    Objective-C实现2 个数字之间的算术几何平均值算法(附完整源码)
    查看>>
    Objective-C实现2d 表面渲染 3d 点算法(附完整源码)
    查看>>
    Objective-C实现2D变换算法(附完整源码)
    查看>>
    Objective-C实现3n+1猜想(附完整源码)
    查看>>
    Objective-C实现3n+1猜想(附完整源码)
    查看>>
    Objective-C实现9x9乘法表算法(附完整源码)
    查看>>
    Objective-C实现9×9二维数组数独算法(附完整源码)
    查看>>
    Objective-C实现A*(A-Star)算法(附完整源码)
    查看>>