【Python版本】3.6
【遇到的问题】
客户端和服务器端都遇到:TypeError: a bytes-like object is required, not 'str'
【解决方案】
参考:https://*.com/questions/13274553/python-3-3-socket-typeerror
创建TCP服务器端:
from socket import *
from time import ctime host = ''
port = 21563
buf_size = 1024
addr = (host, port) tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(addr)
tcpSerSock.listen(5) while True:
print("waiting for connection....")
tcpCliSock, ADDR = tcpSerSock.accept()
print("...connected from:", ADDR) while True:
data = tcpCliSock.recv(buf_size)
print(data)
print(bytes(ctime(), 'utf-8'))
if not data:
break
response = '[%s] %s' % (ctime(), data.decode('utf-8'))
tcpCliSock.send(response.encode('utf-8'))
tcpCliSock.close() tcpSerSock.close()
创建TCP客户端:
from socket import * host = 'localhost'
port = 21563
buf_size = 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('utf-8'))
data = tcpCliSock.recv(buf_size)
if not data:
break
print(data.decode()) tcpCliSock.close()