Python function to check if still alive

610 Views Asked by At

I am running 2 python scripts: one server script and one client(both Windows 10),who connects to the server.

If for example the connection is lost because the client system restarts and the python script does have autorun by startup, how can I reconnect? Because when I do not restart the server it has an error when the client restarted.

Is there a function or trick someone knows to check if the clients script is still running(so I can remotely restart the server)? Or even beter something that doesn't let the server have a connection error if the client system restarts.

shown: simple python chatroom

SERVER

import time, socket, sys
 
new_socket = socket.socket()
host_name = socket.gethostname()
s_ip = socket.gethostbyname(host_name)
 
port = 8080
 
new_socket.bind((host_name, port))
print( "Binding successful!”)
print("This is your IP: ", s_ip)
 
name = input('Enter name: ')
 
new_socket.listen(1) 
 
 
conn, add = new_socket.accept()
 
print("Received connection from ", add[0])
print('Connection Established. Connected From: ',add[0])
 
client = (conn.recv(1024)).decode()
print(client + ' has connected.')
 
conn.send(name.encode())
while True:
    message = input('Me : ')
    conn.send(message.encode())
    message = conn.recv(1024)
    message = message.decode()
    print(client, ':', message)

CLIENT

import time, socket, sys
 
socket_server = socket.socket()
server_host = socket.gethostname()
ip = socket.gethostbyname(server_host)
sport = 8080
 
print('This is your IP address: ',ip)
server_host = input('Enter friend\'s IP address:')
name = input('Enter Friend\'s name: ')
 
 
socket_server.connect((server_host, sport))
 
socket_server.send(name.encode())
server_name = socket_server.recv(1024)
server_name = server_name.decode()
 
print(server_name,' has joined...')
while True:
    message = (socket_server.recv(1024)).decode()
    print(server_name, ":", message)
    message = input("Me : ")
    socket_server.send(message.encode())
1

There are 1 best solutions below

0
wensiso On

You must create a multithread server. In a multithread server, a new independent thread (separated from the main thread) is created for each client.

So, when your client stops, the server finishes only the client's thread, while the main thread keeps running, waiting for new clients.

There are plenty of examples of multithread servers in web. Here are a few examples: