Reputation: 5198
I have a a method which listens to events, and everytime an event happens, it should send data to a socket (its udp, so I don't check if the data was received).
what I have in the event_handler is this:
socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.sendto(data, (IP, PORT))
It seems to me that I need to create a new socket everytime the event is called, because I don't know how much time will pass between two events, So having a global socket variable and send data on the event doesn't guarantee the socket is still up.
The thing is, because I create the socket everytime, should I dispose/close it after sending the data? what is the best way to dispose or close the socket after use?
Upvotes: 0
Views: 1790
Reputation: 535
As already explained by Rob, you do not necessarily need to create a new socket every time.
As per the documentation (https://docs.python.org/3/library/socket.html):
Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly, or to use a with statement around them.
Hence, if you choose to create/close every time, you could do something like this:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as socket:
socket.sendto(data, (IP, PORT))
Upvotes: 2
Reputation: 168646
It seems to me that I need to create a new socket everytime the event is called,
No, it is OK to reuse the previous socket. Remember UDP sockekts are connectionless, so your concern about being disconnected doesn't apply.
The thing is, because I create the socket everytime, should I dispose/close it after sending the data?
Yes, if you are going to create a zillion sockets, please close them as you go. Otherwise you will run out of file descriptor slots, a limited resource in your process.
Upvotes: 1