Python - 通过TCP连接读取json对象(使用正则表达式?)

时间:2016-07-26 07:28:31

标签: python json tcp

我的客户端通过TCP发送json对象。每个对象都具有以下形式:

public class SumConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (values[0] != DependencyProperty.UnsetValue && values[1] != DependencyProperty.UnsetValue && values[2] != DependencyProperty.UnsetValue)

            return ((int)values[0] + (int)values[1]).ToString();

        else
            return DependencyProperty.UnsetValue;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我想写一个端口11111的python服务器,能够获取这些对象并单独解析它们。

任何人都可以帮忙填写完整的代码吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

您可以使用SocketServer包。文档提供了可能对您有用的小示例。以下是tcp服务器的扩展示例:

import SocketServer
import os
import logging
import json

FORMAT = '[%(asctime)-15s] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)


class MyServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    # By setting this we allow the server to re-bind to the address by
    # setting SO_REUSEADDR, meaning you don't have to wait for
    # timeouts when you kill the server and the sockets don't get
    # closed down correctly.
    allow_reuse_address = True

    request_queue_size = 10

    def __init__(self, port):
        self.host = os.uname()[1]
        self.port = port

        SocketServer.TCPServer.__init__(self, (self.host,self.port), MyTCPHandler)

        logging.info( "Server has been started on {h}:{p}".format(h=self.host,p=self.port) )


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
        # max length is here 2048 chars
        s = self.request.recv(2048).strip()

        logging.info( "received: {d}".format(d=s) )

        # here you may parse the received string
        obj = json.loads( s )

        # here just send something back to server 
        self.request.sendall("got it")


PORT = 11111

if __name__ == "__main__":
    # Create the server, binding to localhost on port 11111
    #server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server = MyServer( PORT )

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

答案 1 :(得分:0)

您可以使用flaskRESTful。随意深入研究文档:http://flask-restful-cn.readthedocs.io/en/0.3.4/

特别是完整的示例为您提供了足够的信息来实现您的目标:(http://flask-restful-cn.readthedocs.io/en/0.3.4/quickstart.html#full-example

from flask import Flask
from flask_restful import reqparse, abort, Api, Resource

app = Flask(__name__)
api = Api(app)

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

parser = reqparse.RequestParser()
parser.add_argument('task')


# Todo
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        return TODOS[todo_id]

    def delete(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        del TODOS[todo_id]
        return '', 204

    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201


# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    def get(self):
        return TODOS

    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201

##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')


if __name__ == '__main__':
    app.run(debug=True)