使用Python记录套接字处理程序收到奇怪的字符

时间:2014-08-26 13:53:10

标签: python python-2.7

我正在使用python(2.7)并需要将消息记录到远程服务器。我正在使用logging.handlers库,但消息很奇怪。现在我正在使用python文档网站上提供的SocketServer代码。

import logging
import logging.handlers

class TestMan():
    def __init__(self,xmlString):

        formatter = logging.Formatter('%(levelname)s : %(name)s - %(asctime)s - %(message)s')

        logging.basicConfig(filename='test.log',level=logging.DEBUG,format='%(levelname)s : %(name)s - %(asctime)s - %(message)s')
        log = logging.getLogger(__name__)

        socket = logging.handlers.SocketHandler('localhost',1030)
        socket.setLevel(logging.INFO)
        socket.setFormatter(formatter)

        log.addHandler(socket)
        log.info("Starting Test")

收到以下内容(无法粘贴文字,因此拍摄了一个屏幕截图)

http://i.imgur.com/W65K6iC.png

服务器代码:

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 1030

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

1 个答案:

答案 0 :(得分:0)

SocketHandlers发送的数据在发送之前被腌制。

https://docs.python.org/2/library/logging.handlers.html#logging.handlers.SocketHandler

  

emit()修补记录的属性字典并将其写入   二进制格式的套接字。如果套接字有错误,   默默地丢弃数据包。如果先前丢失了连接,   重新建立连接。在接收时取消记录   结束LogRecord,使用makeLogRecord()函数。