python创建TCP服务器
2020-02-02 17:13
573 查看
python创建TCPSever,python2和python3基本相同,除了以下区别:
- python2引用SocketServer库,python3引用socketserver库
- 发送字符串,python2可直接调用self.wfile.write(content),python3需调用self.wfile.write(content.encode()),否则会出现需要传入参数错误:“TypeError: a bytes-like object is required, not ‘str’”
创建tcp服务器的代码如下:
import struct import time from SocketServer import (TCPServer as TCP, StreamRequestHandler as SRH) # python2 from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH) # python3 HOST = 'localhost' PORT = 9984 ADDR = (HOST, PORT) class MyRequestHandler(SRH): def handle(self): print('...connected from:', self.client_address[0]) self.SendData() def TrasAllpluse(self): pulseNum = 0 try: while True: content = “This is data” self.wfile.write(content) # python2没问题, python3要崩溃 self.wfile.write(content.encode()) # python3没问题 time.sleep(0.0005) except: print("---- error ----\n") tcpServ = TCP(ADDR, MyRequestHandler) print('waiting for connection...') tcpServ.serve_forever()
- 点赞 1
- 收藏
- 分享
- 文章举报
相关文章推荐
- python应用系列教程——python使用socket创建tcp服务器和客户端
- python3+PyQt5 创建网络应用-TCP客户端和TCP服务器
- python使用socket创建tcp服务器和客户端
- python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器
- python 创建TCP服务器、客户端程序
- python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器实例
- python 创建:udp tcp服务器 线程 进程 进程池 互斥锁 协程
- 【1】Python创建简单TCP服务器与TCP客户端
- python socket 创建tcp服务器和客户端改进版(实现半双工聊天)
- python3 用socketserver框架建立TCP,UDP服务器
- Python TCP服务器、客户端程序
- Python实现多线程/多进程的TCP服务器
- python socket之tcp服务器与客户端demo
- 用python模拟TCP 服务器跟 TCP连接
- python下的TCP传输(分别做服务器与客户端)
- Python3编写TCP、UDP客户端和服务器
- node.js中net模块创建服务器和客户端(TCP)
- python实现可将字符转换成大写的tcp服务器实例
- python web编程 创建一个web服务器
- 创建一个简单的Python服务器