Home > Back-end >  Both client and server works on one file
Both client and server works on one file

Time:01-03

So I have a program using sockets, it only accept connections, the server.py file listen to a client.py file, but what if I want it to do it that both files can listen and connect.

For example: here is my server.py

 def main():
    print("[STARTING] Server is starting...")
    """ Starting a TCP socket """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server.bind(ADDR)

    server.listen()
    print("[LISTENING] Server is listening...")

    
    while True:
        """ Accept the connection from the client """
        conn, addr = server.accept()
        addr = socket.gethostname()
        print(f"[NEW CONNECTION] {addr} connected.")

and this is my client.py

 def main():
    """ Staring a TCP socket. """
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while True:
        """ Connecting to the server. """
        client.connect(ADDR)

How can I do both of them in only one file like "Server-Client.py". So if I want to use in one computer Server-Client.py as a client it can be use a a client, and if I want to use Server-client.py as a server on another computer it can be use as a server and the other way around.

any ideas?

CodePudding user response:

Put the server code in one function and the client code in another function. Then call the appropriate function based on whether the user asked for "client" or "server".

import sys

def client():
    # client code here

def server():
    # server code here

if __name__ == '__main__':
    if sys.argv[1] == 'client':
        client()

    elif sys.argv[1] == 'server':
        server()
  • Related