Object-oriented networking

后端 未结 7 1302
臣服心动
臣服心动 2021-02-05 11:07

I\'ve written a number of networking systems and have a good idea of how networking works. However I always end up having a packet receive function which is a giant switch stat

7条回答
  •  日久生厌
    2021-02-05 11:47

    When you are doing OOP, you try to represent every thing as an object, right? So your protocol messages become objects too; you'll probably have a base class YourProtocolMessageBase which will encapsulate any message's behavior and from which you will inherit your polymorphically specialized messages. Then you just need a way to turn every message (i.e. every YourProtocolMessageBase instance) into a string of bytes, and a way to do reverse. Such methods are called serialization techniques; some metaprogramming-based implementations exist.

    Quick example in Python:

    from socket import *
    sock = socket(AF_INET6, SOCK_STREAM)
    sock.bind(("localhost", 1234))
    rsock, addr = sock.accept()
    

    Server blocks, fire up another instance for a client:

    from socket import *
    clientsock = socket(AF_INET6, SOCK_STREAM)
    clientsock.connect(("localhost", 1234))
    

    Now use Python's built-in serialization module, pickle; client:

    import pickle
    obj = {1: "test", 2: 138, 3: ("foo", "bar")}
    clientsock.send(pickle.dumps(obj))
    

    Server:

    >>> import pickle
    >>> r = pickle.loads(rsock.recv(1000))
    >>> r
    {1: 'test', 2: 138, 3: ('foo', 'bar')}
    

    So, as you can see, I just sent over link-local a Python object. Isn't this OOP?

    I think the only possible alternative to serializing is maintaining the bimap IDs ⇔ classes. This looks really inevitable.

提交回复
热议问题