socket

本文详细解析了TCP时间戳服务端与客户端在Python中遇到的常见错误,包括类型错误,以及如何通过正确编码发送和接收的数据来解决这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、TCP时间戳客户端问题

from socket import *
from time import ctime

HOST = 'localhost'
PORT = 211
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
	data = input('> ')
	if not data:
		break
	tcpCliSock.send(data)
	data = tcpCliSock.recv(BUFSIZ)
	if not data:
		break
	print(data)
tcpCliSock.close()

报错:

Traceback (most recent call last):
  File "TCP客户端.py", line 21, in <module>
    tcpCliSock.send(data)
TypeError: a bytes-like object is required, not 'str'

解决方式:

tcpCliSock.send(data.encode())

二、TCP时间戳服务器问题

from socket import *
from time import ctime
#任意可用地址
HOST = ''
#端口号
PORT = 210
#缓冲区大小设置
BUFSIZ = 1024
ADDR = (HOST,PORT)
#TCP服务器套接字
tcpSerSock = socket(AF_INET,SOCK_STREAM)
#将套接字绑定到服务器地址
tcpSerSock.bind(ADDR)
#开启TCP监听器的调用,传入链接请求的最大数
tcpSerSock.listen(5)

while True:
	print('waiting for connecting...')
	#等待客户端连接
	tcpCliSock,addr = tcpSerSock.accept()
	print('..connected from:',addr)

	while True:
		#返回客户端发送的消息
		data =  tcpCliSock.recv(BUFSIZ)
		if not data:
			break
		#加时间戳
		tcpCliSock.send('[%s] %s' % (ctime(),data))

	tcpCliSock.close()
tcpSerSock.close()

报错:

Traceback (most recent call last):
  File "TCP时间戳服务器.py", line 34, in <module>
    tcpCliSock.send('[%s] %s' % (ctime(),data))
TypeError: a bytes-like object is required, not 'str'

解决方式:

tcpCliSock.send(('[%s] %s' % (ctime(),data)).encode())

三、sockserver时间戳TCP服务器

from socketserver import (TCPServer as TCP,BaseRequestHandler as BRH)
from time import ctime

HOST = ''
PORT = 27
ADDR = (HOST,PORT)

class MyRequestHandler(BRH):
	"""docstring for MyRequestHandler"""
	def handle(self):
		print('...connected from:',self.client_address)
		#使用recv获取客户端消息,send将字符串发送回客户端
		self.request.send(('[%s] %s' % (ctime(),self.request.recv(1024))).encode())

tcpServ = TCP(ADDR,MyRequestHandler)
print('waiting for connection...')
tcpServ.serve_forever()

四、sockserver时间戳TCP服务器端

from socket import *

HOST = 'localhost'
PORT = 27
BUFSIZE = 1024
ADDR = (HOST,PORT)

while True:
	tcpCliSock = socket(AF_INET,SOCK_STREAM)
	tcpCliSock.connect(ADDR)
	data = input('> ')
	if not data:
		break
	tcpCliSock.send(('%s\r\n' % data).encode())
	data = tcpCliSock.recv(BUFSIZE)
	if not data:
		break
	print(data.strip())
	tcpCliSock.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值