How to keep code running on client when server is offline - python

So i have a server and client program where the two programs communicate with each other.
my problem is when the server disconnects/goes offline the clients program immediately stops running.
how can i make it so the client program keeps running after the server goes off and keeps trying to connect every 20 seconds lets say so when the server goes back online it reconnects. Edit: I forgot to mention I know how to reconnect the main issue is getting the code to keep running instead of stoping when socket disconnects. Also I know for a fact the whole code works. It's If I close the terminal of the server program, then the clients program stops too.
part of client code to reconnect:
import socket
import os
import sys
import subprocess
import time
from time import sleep
s = socket.socket()
host = '192.168.2.16'
port = 9999
connected = False
while connected == False:
try:
s.connect((host,port))
connected = True
except socket.error:
sleep(5)
part of the server code:
import socket
import sys
import os
import threading
import time
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1,2]
queue = Queue()
all_connections = []
all_adresses = []
def socket_create():
try:
global s
global host
global port
host = '0.0.0.0'
port = 9999
s = socket.socket()
except socket.error as msg:
print("Error: " + str(msg))
def socket_bind():
try:
global host
global s
global port
print("Binding Socket To Port " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding Error: " + str(msg) + '/n' + "Trying Again...")
socket_bind()
def accept_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_adresses[:]
while 1:
try:
conn, address = s.accept()
conn.setblocking(1)
all_connections.append(conn)
all_adresses.append(address)
print("\nConnection has been established: " + address[0])
except:
print("Error accepting connections")
and error:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

Simple answer i found.
use try and except. simple as that.

Related

TCP server gets stuck until a second client makes a request

This is the client
from socket import *
import sys
clientsocket = socket(AF_INET, SOCK_STREAM)
host = "localhost"
port = 10000
message = "Hello"
try:
clientsocket.connect((host,port))
except Exception as data:
print (Exception,":",data)
print ("try again.\r\n")
sys.exit(0)
clientsocket.send(message.encode())
print(message.encode())
response = clientsocket.recv(1024)
print (response)
clientsocket.close()
This is the server
from socket import *
import time
client_facing_port = 10000
router_client_socket = socket(AF_INET, SOCK_STREAM)
router_client_socket.bind(("localhost", client_facing_port))
print ('the router is up on port:',client_facing_port)
router_client_socket.listen(0);
while True:
print ('Ready to serve...')
connectionSocket, addr = router_client_socket.accept()
print(router_client_socket.accept())
try:
message = connectionSocket.recv(1024)
if len(message.split())>0:
print (message,'::',message.split()[0])
connectionSocket.send("Hello to you too".encode())
connectionSocket.send("\r\n".encode())
connectionSocket.close()
except IOError:
connectionSocket.send("something went wrong")
connectionSocket.close()
router_client_socket.close()
connectionSocket.close()
Very basic, I'm just trying to understand how sockets work in python.
Here's the problem, if I fire up the server the console prints
the router is up on port: 10000
Ready to serve...
and when I start the client its console prints
b'Hello'
basically the server gets stuck on connectionSocket, addr = router_client_socket.accept()
here's what I don't get, if I fire up a second client the console (of the second client) reads
ConnectionResetError: [WinError 10054] An existing connection was
forcibly closed by the remote host
which makes sense because the server is not multithread and can only handle one client at any given time since I used router_client_socket.listen(0), but the transaction between the first client and the server gets unstuck and completed! The first client receives the "hello to you too" message and prints it out.
What's causing this?
this is on python 3.9 using Spyder on Anaconda

Why do i keep getting [Erno 111] connection refused while trying to connect my python client to server?

I'm able to start up the server script and get it running no problem, but every time i try to connect with my client script it keeps saying connection refused. I tried running the script on both Linux and windows. For the client and server I tried changing the HOST variable by using just "localhost" as well as gethostbyname.
import socket
from time import ctime
from random import *
PORT = 2222
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
def random_integer_division():
random.randint(1,500)
x = random.randint(1,500)
y = random.randint(1,500)
print(x)
print(y)
if x>y:
return(x//y)
else:
return(y//x)
s.bind(ADDRESS)
s.listen(7)
while True:
print("Waiting for connection. . .")
c, addr = s.accept()
#prints clients address
print(f'... conneceted form: {addr}')
c.send(bytes(f'Information returned form server: \n{str(random_integer_division())}'))
print("CLient disconnected")
c.close()
print("\nClient connection closed")
import socket
from codecs import decode
#HOST = "localhost"
PORT = 2222
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
#calling socket to create a bew sicket object
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(ADDRESS)
dayAndTime = decode(s.recv(BUFSIZE), "ascii")
print(dayAndTIme)
s.close()
print("\nConnection to server closed")
That means your server wasn't active when trying to connect with the client.
Your code has a few typos in it which are problematic but otherwise it just needs to be split into two separate files.
I split them and cleaned up a bit in the blocks below, which should work. I made some inline notes where I made changes. Be sure to run the server first, and then run the client in a separate terminal.
client.py
import socket
PORT = 2222
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
#calling socket to create a new socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDRESS)
dayAndTime = s.recv(BUFSIZE).decode("utf-8") # changed decode method
print(dayAndTime) # you had a type here
s.close()
print("\nConnection to server closed")
server.py
import socket
import random # you had the wrong import here
PORT = 2222
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = socket.gethostbyname("localhost")
ADDRESS=(HOST,PORT)
def random_integer_division(): # unneeded code here
x = random.randint(1,500)
y = random.randint(1,500)
print(x)
print(y)
if x>y:
return(x//y)
else:
return(y//x)
s.bind(ADDRESS)
while True:
s.listen(7) # moved this inside the while loop.
print("Waiting for connection. . .")
c, addr = s.accept()
#prints clients address
print(f'... conneceted form: {addr}')
# changed the method used to encode string
c.send(f'Information returned form server: \n{str(random_integer_division())}'.encode("utf-8")))
print("Client Disconnected")
c.close()
print("\nClient connection closed")

Python Chat Room "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host"

I'm trying to make a chat room that works on localhost with threading and socket. Here is the code:
# Server side
import threading
import socket
host = 'localhost'
port = 11298
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicks = []
def broadcast(msg):
for client in clients:
client.send(msg)
def handle(client):
while True:
try:
msg = client.recv(1024)
broadcast(msg)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nick = nicks[index]
broadcast(f'{nick} has left.'.encode('utf-8'))
nicks.remove(nick)
break
def recv():
while True:
print('The chat room is online ...')
client, address = server.accept()
print(f'You are connected to {str(address)}')
client.send('nick'.encode('utf-8'))
nick = client.recv(1024)
nicks.append(nick)
clients.append(client)
broadcast(f'{nick} has joined.'.encode('utf-8'))
client.send('You have been connected!'.encode('utf-8'))
thread = threading.Thread(target = handle(), args = (client))
thread.start()
if __name__ == "__main__":
recv()
# Client side
import threading
import socket
nick = input('Choose a nickname: ')
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 11298))
def cl_recv():
while True:
try:
msg = client.recv(1024).decode('utf-8')
if msg == 'nick':
client.send(nick.encode('utf-8'))
else:
print(msg)
except:
print("Something went wrong! Bummer.")
client.close()
break
def cl_send():
while True:
msg = f'{nick}: {input("")}'
client.send(msg.encode('utf-8'))
receive_th = threading.Thread(target = cl_recv)
receive_th.start
Whenever I run the code (one cmd window for the server and two for the clients to test it out) it gives me this error:
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I'm guessing it's a problem with the client closing the server, but I'm using client.connect. I've looked at the code multiple times and can't figure out how to fix it.
This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection.

The socket server on ubuntu can't be connected

the code of socket-server and the code of socket-client can run perfectly on my localhost, but when I run the code of socket-server on Ubuntu server, the code of socket-client on my localhost can't connect to Ubuntu server.And the code of socket-client on Ubuntu Server can't connect to my localhost Server.
socket-server.py
import socket
import threading
def bbs(conn):
user_list.append(conn)
try:
while 1:
msg = conn.recv(1024)
if msg:
for user in user_list:
user.send(msg)
except ConnectionResetError:
user_list.remove(conn)
conn.close()
user_list = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 18000))
server.listen()
while 1:
conn, addr = server.accept()
t = threading.Thread(target=bbs, args=(conn,))
t.start()
socket-client.py
import socket
import threading
import time
def send_msg():
while 1:
msg = input()
client.send((name + ':' + msg).encode('utf-8'))
def recv_msg():
while 1:
msg = client.recv(1024)
if msg:
try:
print(msg.decode('utf-8'))
time.sleep(1)
except UnicodeDecodeError:
pass
name = input('请输入你的昵称:')
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('10.26.8.132', 18000))
sendmsg_thread = threading.Thread(target=send_msg)
recvmsg_thread = threading.Thread(target=recv_msg)
sendmsg_thread.start()
recvmsg_thread.start()
Server is always wait for connection, Client report an error:
TimeoutError: [WinError 10060] The connection attempt failed because the connecting party did not respond correctly after a period of time or because the connecting host did not respond.
Wang if this works without issue on your localhost, but not over a network connection, it might be a firewall issue on both client & server. You can use 'nc' (netcat) for testing the connection from client to the server.

Python3 Portscanner can't solve the socket pr0blem

When I run this code I am getting this socket error:
[WinError 10038] An operation was attempted on something that is not a socket
but even if I delete the s.close() it gives me wrong results.
It is a port scanner that are going to try connecting to all ports on the server I want to scan. And the ones that i'm getting connection from is stored in a list. But for some reason it is giving me wrong results. can someone please help me.
import socket
import threading
def scan_for_open_ports():
#Creating variables
OpenPorts = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
global port
global OpenPorts
port = 1
#Scanning
for i in range(65534):
try:
s.connect((host, port))
s.shutdown(2)
OpenPorts.append(port)
print(str(port) + 'is open.')
s.close()
port += 1
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
#Giving the user results
print('------Open porst-----\n')
print(OpenPorts)
That's because you're closing your socket inside the loop with s.close() and you're not opening it again and you try to connect with a socket that's closed already. you should close the socket when you're done with it at the end of the loop, i also amended your code to make OpenPorts global and remove the unnecessary port variable you define and increment inside your for loop
import socket
OpenPorts = []
def scan_for_open_ports():
# Creating variables
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
# Scanning
for port in range(1, 65534):
try:
s.connect((host, port))
OpenPorts.append(port)
print(str(port) + 'is open.')
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
# Giving the user results
print('------Open ports-----\n')
print(OpenPorts)
scan_for_open_ports()

Categories

Resources