0

I am new to python and I am writing a socket code in Python. I have three different machines(Machine A, Machine B and Machine c) with IP address as 1.1.1.1, IPb and IPc, respectively.

Now, I want my Machine A to run one thread as Server A and a client thread as Client A. The same code will be run in Machine B and C. Client A will check if Server B is listening or not. If Server B is not listening then try to connect to server c. If server c is not listening then connect to server A and do something.

My code is below:

import os, sys, socket, time, threading
Host = 1.1.1.1
PORT = 1111
threads = []
threadss =[]
def server():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        while 1:
            print ("Listening")
            s.listen()
            conn, addr = s.accept()
            with conn:
                print("connected")
                data = conn.recv(1024)
                if data == b'please sleep':
                    time.sleep(300)
                if data == b'do something': 
                    print("do something")
def client():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while 1:
        try:
           s.connect((IPaddress of Machine B, Port of machineB))
        except Exception as inst:
            print("machine B not ready")
            try:
               s.connect((IP address of Machine C, Port of MAchine c))
            except Exception as inst:
               print("machine c not ready"))
               s.connect(('1.1.1.1', 1111))
               s.sendall(b'do something')


serv = threading.Thread( target=server)
threads.append(serv)
serv.start()
print("starting the thread serv")
time.sleep(3)
cli=threading.Thread(target = client)
threadss.append(cli)
cli.start()
print("client started")

I am not able to do that case where : Client A checks if Server B and Server c and if anyone of them is active then it sends message to server A to sleep.

Thanks in advance for any help!!

hazzy
  • 107
  • 1
  • 8
  • 1
    Can you be more specific about which part you’re struggling with? As an aside, using `except Exception` like that is bad practice, see, for example https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except – AMC Feb 28 '20 at 03:40
  • I am struggling in the scenario when Client A is able to connect to server B. In this case client A should send message to Server A "please sleep" – hazzy Feb 28 '20 at 04:24

0 Answers0