博客
关于我
Python标准库socketserver实现UDP协议时间服务器
阅读量:275 次
发布时间:2019-03-01

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

Python标准库socket与socketserver的案例分析

长时间之前,我们推送过一个使用标准库socket实现UDP协议时间服务器的代码案例。随后,我们又通过socketserver进行了更高一级的封装,展示了如何更简便地编写服务端代码。本文将通过改写时间服务器案例,详细介绍socketserver的用法,并展示其优势。

服务端代码

import socketserverclass TimeServer(socketserver.BaseHTTPRequestHandler):    def do_GET(self):        self.send_header('Content-type', 'text/plain')        self.send_data('当前时间:' + self.time().strftime('%Y-%m-%d %H:%M:%S'))        self.end_headers()if __name__ == "__main__":    server = socketserver.TCPServer(('', 8080))    server.serve()

客户端代码

import socketdef get_time():    host = 'localhost'    port = 8080    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    s.connect((host, port))    response = s.recv(1024).decode()    s.close()    print('从服务器获取的时间:' + response)if __name__ == "__main__":    get_time()

运行情况

通过上述代码,可以实现一个简单的时间服务器和客户端。服务器接收客户端的连接,返回当前时间;客户端则向服务器发送请求,接收并显示时间信息。

推荐书籍

董付国老师的Python系列图书涵盖了从基础到进阶的多个主题,适合不同水平的读者。以下是部分推荐:

  • 《Python程序设计(第2版)》

    清华大学出版社,2016年出版,2019年度畅销图书。

  • 《Python程序设计基础(第2版)》

    清华大学出版社,2018年出版,2019年度畅销图书。

  • 《Python可以这样学》

    清华大学出版社,2017年出版。

  • 《中学生可以这样学Python》

    清华大学出版社。

  • 《Python程序设计实例教程》

    机械工业出版社。

  • 温馨提示

    关注本公众号“Python小屋”,通过菜单“最新资源” == > “历史文章”可以快速查看分专题的1000篇技术文章列表(可根据关键字在页面上搜索感兴趣的文章),通过“最新资源” == > “微课专区”可以免费观看500节Python微课,通过“最新资源” == > “培训动态”可以查看近期Python培训安排,通过“最新资源” == > “教学资源”可以查看Python教学资源。

    如需了解更多技术文章和培训信息,请持续关注“Python小屋”公众号。

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

    你可能感兴趣的文章
    npm和yarn清理缓存命令
    查看>>
    npm和yarn的使用对比
    查看>>
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>