I have a python program with many threads. I was thinking of creating a socket, bind it to localhost, and have the threads read/write to this central location. However I do not want this socket open to the rest of the network, just connections from 127.0.0.1
should be accepted. How would I do this (in Python)? And is this a suitable design? Or is there something a little more elegant?
In Python, you use socket. setblocking(False) to make it non-blocking.
To close the connection, break the while loop. Garbage collection will remove the thread or process but join will ensure none get left behind. Persistent sockets close when the user closes them or they timeout.
The first step is to import the socket module and then create a socket just like you did while creating a server. Then, to create a connection between the client-server you will need to use the connect() method by specifying (host, port).
SOCK_STREAM. Provides sequenced, two-way byte streams with a transmission mechanism for stream data. This socket type transmits data on a reliable basis, in order, and with out-of-band capabilities. In the UNIX domain, the SOCK_STREAM socket type works like a pipe.
Given a socket created with socket.socket()
, you can use bind()
before listening:
socket.bind(('127.0.0.1', 80))
Using the address 127.0.0.1
indicates that the socket should bind to the local interface only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With