马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 htyj0 于 2021-3-25 15:17 编辑
想写一个简单的TCP通信程序,客户端输入字符串,服务器加上时间戳后将字符串原样返回。
客户端程序:
# 客户端程序TCP_Client.pyimport socket as s
from time import ctime
HOST = '127.0.0.1'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpCliSock = s.socket(s.AF_INET, s.SOCK_STREAM)
tcpCliSock.connect(ADDR)
while(True):
data = input('> ')
#data = b'\x01\x02\x03'
if not data:
print('ivalid data')
break
tcpCliSock.send(data.encode())
data = tcpCliSock.recv(BUFSIZE)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()
服务器端程序:# 服务器程序 TCP_Server.py
import socket as s
from time import ctime
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpServerSock = s.socket(s.AF_INET, s.SOCK_STREAM)
tcpServerSock.bind(ADDR)
tcpServerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpServerSock.accept()
print('...Connected from: ', addr)
while True:
data = tcpCliSock.recv(BUFSIZE)
str_data = data.decode()
if not data:
break
print('data received: ', str_data)
tcpCliSock.send('[%s] : %s' % (ctime(), str_data))
tcpCliSock.close()
tcpServerSock.close()
在客户端任意输入一个字符串时,服务器可以显示,但会提示错误。
服务器端显示:
================== RESTART: F:\00_AppData\python\TCP_Server.py =================
waiting for connection...
...Connected from: ('127.0.0.1', 50416)
data received: hello
Traceback (most recent call last):
File "F:\00_AppData\python\TCP_Server.py", line 29, in <module>
tcpCliSock.send('[%s] : %s' % (ctime(), str_data))
TypeError: a bytes-like object is required, not 'str'
>>>
请大神帮忙看一下,感激不尽。。
报错提示send接受字节对象,不是字符串,试试先将字符串编码再发送(未测试) # 服务器程序 TCP_Server.py
import socket as s
from time import ctime
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpServerSock = s.socket(s.AF_INET, s.SOCK_STREAM)
tcpServerSock.bind(ADDR)
tcpServerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpServerSock.accept()
print('...Connected from: ', addr)
while True:
data = tcpCliSock.recv(BUFSIZE)
str_data = data.decode()
if not data:
break
print('data received: ', str_data)
tcpCliSock.send(('[%s] : %s' % (ctime(), str_data)).encode('utf-8'))
tcpCliSock.close()
tcpServerSock.close()
|