Skip to content
Lucio Santi edited this page Aug 1, 2014 · 3 revisions

PTC WikiUsage

Any application can use the protocol through the Socket wrapper (see ptc_socket). Since it implements the most common primitives of traditional Python sockets, the use experience should be essentially analogous. Nevertheless, every program using PTC sockets must be executed with enough permissions to instantiate raw sockets. Besides, for the purpose of ensuring proper termination of the program, we suggest to use PTC sockets inside with blocks. An alternative is to make ad-hoc calls to close or free in order to finish the connection and shut down the threads involved. If neither of these options is performed, the program might hang forever because of those threads.

In what follows we show a small example on which a script binds a PTC socket to port 6677 of localhost and another script declares and connects a new socket to that port. Both, then, send some data and finally they display the information received:

# Script that binds a socket to port 6677 of localhost.
from ptc import Socket
to_send = 'Lorem ipsum dolor sit amet'
received = str()
with Socket() as sock1:
    sock1.bind(('127.0.0.1', 6677))
    sock1.listen()
    sock1.accept()
    received += sock1.recv(15)
    sock1.send(to_send)
    sock1.close()
print 'sock1 received: %s' % received
# Script opens a socket and connects it to port 6677 of localhost.
from ptc import Socket, SHUT_WR
to_send = 'foo bar baz'
received = str()
with Socket() as sock2:
    sock2.connect(('127.0.0.1', 6677))
    sock2.send(to_send)
    received += sock2.recv(10)
    # We close the write stream but we can keep receiving further
    # data.
    sock2.shutdown(SHUT_WR)
    received += sock2.recv(20)
print 'sock2 received: %s' % received

Once finished, the first script should show sock1 received: foo bar baz and, the second one, sock2 received: Lorem ipsum dolor sit amet.

Clone this wiki locally