python网络编程遇到问题
本帖最后由 htyj0 于 2021-3-25 15:17 编辑想写一个简单的TCP通信程序,客户端输入字符串,服务器加上时间戳后将字符串原样返回。
客户端程序:
# 客户端程序TCP_Client.py
import 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'
>>>
请大神帮忙看一下,感激不尽。。
tcpCliSock.send('[%s] : %s' % (ctime(), str_data))
只能传字节参数,你需要在外面转换成字节, 然后send 报错提示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() hrp 发表于 2021-3-25 16:35
报错提示send接受字节对象,不是字符串,试试先将字符串编码再发送(未测试)
是这样的,用改过的代码测试已通过。万分感谢!
页:
[1]