TCPServer+StreamRequestHandler 网络编程
注意的几点:
1.StreamRequestHandler类支持像操作文件对象那样操作输入套字节;
2.网络传输的数据需时bytes;
3.客户端和服务器端发送的消息都必须加上回车和换行符号
4.socketserver的请求处理器的默认行为是接受连接,得倒请求,然后关闭连接,而不是一直保持连接状态。从而多个连接可以并发进行。
服务器端代码:
from socketserver import (TCPServer, StreamRequestHandler)
from time import ctime
HOST = ''
PORT = 12345
ADDR = (HOST, PORT)
class MyHandler(StreamRequestHandler):
def handle(self):
print ('...connect from:', self.client_address) #self.client_address 得到客户端地址
data = '[%s]%s' % (ctime(), self.rfile.readline().decode('UTF-8')) #rfile.reaadline()方法来读取客户消息
self.wfile.write(bytes(data, 'UTF-8'))#wfile.write()发送消息,在python3x后必须将str转化为bytes对象才能在网络中传续
tcpSer = TCPServer(ADDR, MyHandler)
print ('waiting for connecting...')
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()