您的位置:首页 > 编程语言 > Python开发

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
  • 收藏
  • 分享
  • 文章举报
常思大妹子 发布了11 篇原创文章 · 获赞 7 · 访问量 219 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: