博客
关于我
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/

    你可能感兴趣的文章
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>