简体   繁体   中英

Client-Server socket setup, how to respond to a determined client

This question has been edited to focus in a simpler problem

So I have a basic client-server socket installation, in which the client send a JSON like {'id': '1', 'value': 'A'} . At the server side, if I receive a message with id 2 I want to send a message to the client with id 1 , telling him that his new value is C .

This message should be "private", ie, only id 1 should receive it, no broadcasting allowed.

How should I approach this problem? How could I keep track of the connections at the server side so that I could send a message to a determined client? The problem is that it's the server the one sending the message to the client, not responding to a client's message. I guess it must be with some combination of threading and queues, but still haven't figured out how to do it.

This is the code I have right now at the server, keeping track of the clients using a dict, but it's not working (bad file descriptor at the sendall('C') line:

track_clients = {}
while True:
    print "waiting for a connection"
    connection, client_address = sock.accept()
    try:
        print "connection from ", client_address
        data = json.loads(connection.recv(1024))
        track_clients[data['id']] = connection

        if data['id'] == '2':
            conn = track_clients['1']
            conn.sendall('C')
        connection.sendall(json.dumps(data))
    finally:
        connection.close()

You can have a look at channels http://channels.readthedocs.org/en/latest/ . Alongside redis ( https://pypi.python.org/pypi/redis/ )

Have you considered using zeromq for this task? It is easy to use and provides high level implementation of common patterns.

From zeromq guide

ZeroMQ (also known as ØMQ, 0MQ, or zmq) looks like an embeddable networking library but acts like a concurrency framework. It gives you sockets that carry atomic messages across various transports like in-process, inter-process, TCP, and multicast. You can connect sockets N-to-N with patterns like fan-out, pub-sub, task distribution, and request-reply. It's fast enough to be the fabric for clustered products. Its asynchronous I/O model gives you scalable multicore applications, built as asynchronous message-processing tasks. It has a score of language APIs and runs on most operating systems. ZeroMQ is from iMatix and is LGPLv3 open source.

Also it seems like it better to reuse existing libraries because you can focus on your tasks directly while library provides you with all required high-level methods.

The code above is OK. The problem is the connection.close() at the finally statement. Removing it, fixes the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM