#π how do i reconnect to socket when it is disconnected manually from the client side
25 messages Β· Page 1 of 1 (latest)
@celest wedge
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Can you elaborate?
Show the code you have so far and the error message
kill -9 $(ps -A | grep python | awk '{print $1}')
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 6969)
server_socket.bind(server_address)
server_socket.listen(2)
print("Server is listening...")
client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address}")
x = []
while True:
data = client_socket.recv(1024).decode('utf-8')
if data:
print(f"Received: {data}")
x.append(data)
print(x)
client_socket.close()
server_socket.close()
here
If it's disconnected from the client's side, then you cannot reconnect, unless client is also a kind of server (waits for connections). Because normally client only has a temporary port for the current communication
what if the client get disconnected by some tech. issue how do you reconnect then without restarting the server
There's got to be code on the client
Do you really need to be using plain sockets?
i am just learning about them
ty fam
without restarting the server
Just don't kill the server when client disconnects. Does a website closes when you no longer use it? No, it waits for more connections.
You can do it by having a server create a thread for each client, while main thread still waits for connections
Or use select, but it's more tricky
This simple tutorial has an example of loop and starting thread per client, very simple https://docs.python.org/3/howto/sockets.html
while True:
# accept connections from outside
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a threaded server
ct = client_thread(clientsocket)
ct.run()
You'll need to use a cookie to associate clients with reconnections
And you might need message numbers and a buffer so you can resend what's missed and so you know what's missed
interesting im learning socket programming still
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.