tcp服务器端
from socket import *
from time import ctime
HOST = ''
PORT = 2567
BUFSIZE = 1024
ADDR = (HOST, PORT)
tcpServer = socket(AF_INET, SOCK_STREAM)
tcpServer.bind(ADDR)
tcpServer.listen(5)
while True:
print("waiting connection")
tcpClisock, addr = tcpServer.accept()
print('accept from:', addr)
while True:
#从客户端接收过来的信息是二进制形式的
data = tcpClisock.recv(BUFSIZE)
if not data:
break
#发送信息,该信息必须是二进制字符串的形式,也就是send里面的参数
tcpClisock.send('[%s] %s'.encode('utf-8') % (bytes(ctime(),'utf-8'), data))
tcpClisock.close()
tcpServer.close()
tcp客户端
from socket import *
HOST = '127.0.0.1'
PORT = 2567
BUFSIZE = 1024
ADDR = (HOST, PORT)
Clisocket = socket(AF_INET, SOCK_STREAM)
Clisocket.connect(ADDR)
while True:
data = input('> ')
if not data:
break
#发送的信息必须是二进制
Clisocket.send(data.encode(encoding='utf-8'))
data = Clisocket.recv(BUFSIZE)
if not data:
break
print(data)
Clisocket.close()