服务器:
from socket import *
from time import ctime
HOST=''
PORT=12345
ADDR=(HOST,PORT)
BUFSIZE=1024
tcpSerSock=socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connecting....')
tcpCliSock,addr=tcpSerSock.accept()
print('....connect from:',addr)
while True:
data=tcpCloSock.recv(BUFSIZE).decode()
if not data:
break
tcpCliSock.send(('[%s] %s' % (ctime(), data)).encode())
tcpCliSock.close() #注意这里的缩进
tcpSerSock.close()
客户端:
from socket import *
HOST='localhost'
PORT=12345
BUFSIZE=1024
ADDR=(HOST,PORT)
tcpCliSock=socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data=input('请输入:')
if not data:
break
tcpCliSock.send(data.encode())
data=tcpCliSock.recv(BUFSIZE).decode()
if not data:
break
print(data)
tcpCliSock.close()
参考:
Codec.encode(input[, errors])
Encodes the object input and returns atuple (output object, length consumed). Encoding converts a string object to abytes object using a particular character set encoding
Codec.decode(input[, errors])
Decodes the object input and returns atuple (output object, length consumed). Decoding converts a bytes objectencoded using a particular character set encoding to a string object.
input must be a bytes object or one whichprovides the read-only character buffer interface – for example, buffer objectsand memory mapped files.
原文 Python 3中套接字编程中遇到TypeError: ‘str’ does not support the buffer interface的解决办法