注意:
通过self.request.recv()和self.request.send()两个函数来接受和发送消息;
服务器端代码:
from socketserver import (TCPServer, BaseRequestHandler)
from time import ctime
HOST = ''
PORT = 12345
ADDR = (HOST, PORT)
BUFSIZE = 1024
class MyHandler(BaseRequestHandler):
def handle(self):
print('connected from:', self.client_address)
data = '[%s]%s' % (ctime(), self.request.recv(BUFSIZE).decode('UTF-8'))
self.request.send(bytes(data, 'UTF-8'))
tcpSer = TCPServer(ADDR, MyHandler)
print('...waiting fo connection...')
tcpSer.serve_forever()
客户端代码:
from socket import *
HOST = 'localhost'
PORT = 12345
ADDR = (HOST, PORT)
BUFSIZE = 1024
def main():
while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
data = input('>')
if not data:
break;
tcpCliSock.send(bytes(data + '\r\n', 'UTF-8'))
data = tcpCliSock.recv(BUFSIZE).decode('UTF-8')
if not data:
break;
print (data)
tcpCliSock.close()
main()