Change Close Type on Python Socket - python

problemI, want my socket application to close connection with 3 hand-shake close but after the timeout it closes with reset
code
I want it to close connection with 3 hand-shake close

Related

Multithreading with Tkinter - Thread never releases lock

I have a Tkinter app which connects to a proprietary sensor over serial and controls it with Python. I am trying to have a thread which always runs in the background to detect if the connection dies, shows an alert, and allows the user to press a button to re-establish the serial connection (reconnect is also done in another thread). For some reason, the COM monitor thread works fine, and when I unplug the serial cable, it shows a popup and enables the reconnect button as expected, but when I reconnect one or twice, the reconnect thread just stops releasing the lock. I've checked this with print statements.
Here is the code which spawns the thread that does the actual reconnect over serial. This thread is spawned when the reconnect button is pressed.
def spawn_reconnect_to_mote_thread(self):
self.reconnect_thread = threading.Thread(target=self.reconnect_to_mote)
self.reconnect_thread.daemon = True
self.reconnect_thread.name = 'reconnect'
self.reconnect_thread.start()
Here is the reconnect function. We also use a proprietary control software written in python which is why the syntax may look weird. This software has its own thread that is spawned when a connection is made. MOTE_MODEL_MAP just maps the correct control functions to the correct model ID which allows this to be easily extended to different hardware models.
def reconnect_to_mote(self):
with self.lock:
self.connection.close()
self.connection = MOTE_MODEL_MAP[self.mote_model_str ['mote_transport'].Connection({'serial': [self.com_port]})
self.com_model_label['text'] = MOTE_MODEL_MAP[self.mote_model_str]['name']
self.reconnect_button['state'] = 'disabled'
self.scan_button['state'] = 'active'
self.monitor_com = True
This spawns the thread to monitor the COM port. This thread is spawned pretty early on in the app's __init__ once the initial connection is made and the hardware is prepped with some commands.
def spawn_com_monitor_thread(self):
self.com_monitor_thread = threading.Thread(target=self.com_monitor)
self.com_monitor_thread.daemon = True
self.com_monitor_thread.name = 'com monitor'
self.com_monitor_thread.start()
Lastly, this is the actual function running in the thread which monitors the COM port. It just constantly grabs open COM ports and checks if the one we're using exists. If not, it should show a popup, set a flag, and allow the user to click the reconnect button. The reconnect function should then set the flag again. This is to prevent infinite popups while a user reconnects.
def com_monitor(self):
while True:
ports = [port[0] for port in list(list_ports.comports())]
if (self.com_port not in ports) and (self.monitor_com == True):
with self.lock:
self.monitor_com = False
self.scan_button['state'] = 'disabled'
msg.showerror(title='Serial connection died', message='The serial cable has become disconnected. Scanning has been stopped. Please reconnect the cable and reconnect to the mote.')
self.reconnect_button['state'] = 'active'
self.monitor_com = False
I've been banging my head on this for a couple days now with no solution. I haven't done much threading before and would like to do this in a threaded way to allow for maximum responsiveness.
I am running Python 3.6.13.

How to safely exit a socket if the python process is forcibly quit?

I'm attempting to get a simple server up and running with sockets, where it will send out the same information to any connected client. I've successfully managed to handle threads and stopping them in the case of KeyboardInterrupt, but I can't figure out how to close the socket if the script is ended early (such as the python process closed or you force run the script again).
A very basic example would be this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_process.bind(('localhost', 60000))
socket_process.listen(5)
conn, addr = socket_process.accept()
If you run that (on Windows at least), and then hit F5 to run it again, you get error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.. It does eventually close after half a minute or something, but I'd like it to instantly close if the script that spawned it no longer exists.
Even if a timeout is set, it doesn't cause the error to go away any time sooner.
For the record, those types of exit aren't caught by atexit. I'm thinking something similar to the multiprocessing daemon option could work if it exists.

Python: interrupt s.accept()

I have this code:
host, port = sys.argv[1:3]
port=int(port)
s = socket.socket()
s.bind((host,port))
s.listen(5)
while True:
conn, addr = s.accept()
threading.Thread(target=handle,args=(conn,)).start()
I need to stop my code using Ctrl-C, but Python doesn't receive Ctrl-C when it waits for new connection (s.accept()). How can I solve this problem?
In order to stop the socket connection, you can call the shutdown method like so:
s.shutdown(socket.SHUT_WR)
(This SHUT_WR stops all new writes and reads)
However, while your code is running, it is suspended while trying to make the TCP connection. In order to stop it via Ctrl-C, you'll need to run the socket on another thread, giving your main thread the ability to wake up to the interrupt and send the shutdown message.
You can use shutdown() or close() for your need
A wonderful explanation (from AIX 4.3 Communications Programming Concepts) is given below
Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.

Better way of reading UDP data in Python

Is there a better way of listening on a port and reading in UDP data?
I do a
self.udps.bind((self.address,self.port)
ata, addr = self.udps.recvfrom(1024)
It seems to get locked in this state until it gets that data, in a bare script or in a thread.
This works well, but if you want to say get it to stop listening, it won't until it receives data and moves on to realize it needs to stop listening. I've had to send UDP data to the port each time to get it to gracefully shut down. Is there a way to get it to stop listening immediately with a specific condition?
recfrom waits until data arrives on the specified port.
If you don't want it to listen forever, set a timeout:
self.udps.bind((self.address,self.port)
self.udps.settimeout(60.0) # set 1min timeout
while some_condition:
try:
ata, addr = self.udps.recvfrom(1024)
except socket.timeout:
pass # try again while some_condition
else:
# work with the received data ...

python socket server/client protocol with unstable client connection

I have a threaded python socket server that opens a new thread for each connection.
The thread is a very simple communication based on question and answer.
Basically client sends initial data transmission, server takes it run an external app that does stuff to the transmission and returns a reply that the server will send back and the loop will begin again until client disconnects.
Now because the client will be on a mobile phone thus an unstable connection I get left with open threads no longer connected and because the loop starts with recv it is rather difficult to break on lost connectivity this way.
I was thinking on adding a send before the recv to test if connection is still alive but this might not help at all if the client disconnects after my failsafe send as the client sends a data stream every 5 seconds only.
I noticed the recv will break sometimes but not always and in those cases I am left with zombie threads using resources.
Also this could be a solid vulnerability for my system to be DOSed.
I have looked through the python manual and Googled since thursday trying to find something for this but most things I find are related to client and non blocking mode.
Can anyone point me in the right direction towards a good way on fixing this issue?
Code samples:
Listener:
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversocket.bind(addr)
serversocket.listen(2)
logg("Binded to port: " + str(port))
# Listening Loop
while 1:
clientsocket, clientaddr = serversocket.accept()
threading.Thread(target=handler, args=(clientsocket, clientaddr,port,)).start()
# This is useless as it will never get here
serversocket.close()
Handler:
# Socket connection handler (Threaded)
def handler(clientsocket, clientaddr, port):
clientsocket.settimeout(15)
# Loop till client closes connection or connection drops
while 1:
stream = ''
while 1:
ending = stream[-6:] # get stream ending
if ending == '.$$$$.':
break
try:
data = clientsocket.recv(1)
except:
sys.exit()
if not data:
sys.exit()
# this is the usual point where thread is closed when a client closes connection normally
stream += data
# Clear the line ending
stream = base64.b64encode(stream[:-6])
# Send data to be processed
re = getreply(stream)
# Send response to client
try:
clientsocket.send(re + str('.$$$$.'))
except:
sys.exit()
As you can see there are three conditions that at least one should trigger exit if connection fails but sometimes they do not.
Sorry, but I think that threaded idea in this case is not good. As you do not need to process/do a lot of stuff in these threads (workers?) and most of the time these threads are waiting for socket (is the blocking operation, isn't it?) I would advice to read about event-driven programming. According to sockets this pattern is extremly useful, becouse you can do all stuff in one thread. You are communicate with one socket at a time, but the rest of connections are just waiting to data so there is almost no loss. When you send several bytes you just check that maybe another connection requires carrying. You can read about select
and epoll.
In python there is several libraries to play with this nicly:
libev (c library wrapper) - pyev
tornado
twisted
I used tornado in some projects and it is done this task very good. Libev is nice also, but is a c-wrapper so it is a little bit low-level (but very nice for some tasks).
So you should use socket.settimeout(float) with the clientsocket like one of the comments suggested.
The reason you don't see any difference is, when you call socket.recv(bufsize[, flags]) and the timeout runs out an socket.timeout exception is thrown and you catch that exception and exit.
try:
data = clientsocket.recv(1)
except:
sys.exit()
should be somthing like:
try:
data = clientsocket.recv(1)
except timeout:
#timeout occurred
#handle it
clientsocket.close()
sys.exit()

Categories