Python client / server

1

I'm doing a client and a server with sockets.

The client sends an option (1,2,3) and the server returns the result. In option 1 I send a command (ipconfig) and it returns the result, but then to re-execute another command I have to press again 1, and then the new command.

How can I do so that when I press option 1 it allows me to send command and receive the result infinitely, without going to the main menu as it does now?

Main server.

# -*- coding: utf-8 -*-
import logging
from lib.thread_server import Thread_server
from app_settings import settings
logger = logging.getLogger(settings.LOGGING['logger_name'])
import socket

''' Metodo main '''
def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("127.0.0.1", 9999))
    s.listen(2)

    while True:
        sc, addr = s.accept()
        t_server = Thread_server('Thread_server',sc)
        t_server.start()
    s.close()

''' Inicio de la app '''
if __name__ == "__main__":
    main()

Server thread.

# -*- coding: utf-8 -*-
import logging
import threading
import time
# Import configuration file:
from app_settings import settings
# Instance logger:
logger = logging.getLogger(settings.LOGGING['logger_name'])
import os
import subprocess
from lib.thread_1 import Thread_1


class Thread_server(threading.Thread):

    def __init__(self, name, sc):
        threading.Thread.__init__(self)
        self.name = name
        self.sc = sc

    def run(self):
        while True:
            message_recived = self.sc.recv(1024)
            # Condiciones.
            if message_recived == "1":
                while True:
                    # recivo.
                    mensaje1 = self.sc.recv(1024)
                    print(mensaje1)
                    # envio.
                    self.sc.send('correcto')
            elif message_recived == "2":
                print('opcion 2')
            elif message_recived == "3":
                break
            else:
                self.sc.send('Opcion no valida.')
        self.sc.close()

Customer.

# -*- coding: utf-8 -*-
import logging
from app_settings import settings
logger = logging.getLogger(settings.LOGGING['logger_name'])
from lib.thread_1 import Thread_1
import socket
import os 
import time
import sys

def main():
    PORT = 9999
    SERVER = "127.0.0.1"
    SERVER_STATUS = "STOP"
    TIME_WAIT_CONECTING = 1

    while True:
        try:
            # Si el servidor esta encendido.
            s = socket.socket()
            s.connect((SERVER, PORT))
            SERVER_STATUS = "START"
            os.system('cls')
            # Salgo del bucle y doy paso al menu de opciones.
            break
        except Exception:
            os.system('cls')
            print('CONECTING SERVER')
            SERVER_STATUS = "STOP"

    while True:
        print('====== SERVER OPTIONS ======')
        print('- PRESS 1 - Enter comand. ')
        print('- PRESS 2 - ')
        print('- PRESS 3 - EXIT.')
        print('============================')
        # Instanciamos una entrada de datos para que el cliente pueda enviar mensajes.
        mensaje_menu = raw_input("SEND SERVER >> ")

        if mensaje_menu =="1":
            while True:
                mensaje_servidor = raw_input("SEND COMAND >> ")
                # Envio comando.
                s.send(mensaje_servidor)
                mensaje_recivido = s.recv(1024)
                print("SERVER RESPONSE >> " + mensaje_recivido)

        if mensaje_menu =="2":
            mensaje_servidor = raw_input("SEND COMAND >> ")
            # Envio comando.
            s.send(mensaje_servidor)

        if mensaje_menu == "3":
            break

        os.system('cls')

    s.close()

if __name__ == "__main__":
    main()
    
asked by Anónimo 20.09.2017 в 17:10
source

1 answer

0

The problem is that you do not establish a correct feed-back protocol with the server, you never send it the option that you choose, and you do not stop listening for commands from the server. A possible protocol could be:

  • Client sends the option to the server ("1").

  • The server must respond to this by informing that it enters the cycle to enter commands until a keyword is entered. This key must be something other than a command, for example @stop .

  • The client sends messages until the server tells it that it is not listening for commands (due to an error or because the key @stop has been sent by the client.)

  • There are many ways to do this and it will depend to a large extent on how you want exceptions to be answered by both the client and the server. The idea in any case is this, to communicate with the server using keywords that allow you to alter your status.

    The code should look something like this:

    Client:

    while True:
        print('====== SERVER OPTIONS ======')
        print('- PRESS 1 - Enter comand. ')
        print('- PRESS 2 - ')
        print('- PRESS 3 - EXIT.')
        print('============================')
        # Instanciamos una entrada de datos para que el cliente pueda enviar mensajes.
        mensaje_menu = raw_input("SEND SERVER >> ")
    
        if mensaje_menu == "1":
            s.send("1")
            mensaje_recibido = s.recv(1024)
            if mensaje_recibido == "@start":
                print("Servidor a la espera de comandos, ingrese @stop para salir...")
            else:
                print("Error")
    
            while True:
                mensaje_servidor = raw_input("SEND COMAND >> ")
                s.send(mensaje_servidor)
                mensaje_recibido = s.recv(1024)
                if mensaje_recibido == "@stop":
                    break
                print("SERVER RESPONSE >> " + mensaje_recibido)
    

    thread_server.py :

    def run(self):
        while True:
            message_recived = self.sc.recv(1024)
            # Condiciones.
            if message_recived == "1":
                self.sc.send('@start')
                while True:
                    # recivo.
                    mensaje1 = self.sc.recv(1024)
                    if mensaje1 != "@stop":
                        print(mensaje1)
                        self.sc.send('correcto')
                    else:
                        self.sc.send('@stop')
                        break
    

    For option 2 or later establish a similar protocol.

    The output would be something like this:

    ====== SERVER OPTIONS ======
    - PRESS 1 - Enter comand. 
    - PRESS 2 - 
    - PRESS 3 - EXIT.
    ============================
    SEND SERVER >> 1
    Servidor a la espera de comandos, ingrese @stop para salir...
    SEND COMAND >> ipconfig
    SERVER RESPONSE >> correcto
    SEND COMAND >> cd
    SERVER RESPONSE >> correcto
    SEND COMAND >> ping
    SERVER RESPONSE >> correcto
    SEND COMAND >> @stop
    ====== SERVER OPTIONS ======
    - PRESS 1 - Enter comand. 
    - PRESS 2 - 
    - PRESS 3 - EXIT.
    ============================
    SEND SERVER >> 1
    Servidor a la espera de comandos, ingrese @stop para salir...
    SEND COMAND >> ipconfig
    SERVER RESPONSE >> correcto
    SEND COMAND >> @stop
    ====== SERVER OPTIONS ======
    - PRESS 1 - Enter comand. 
    - PRESS 2 - 
    - PRESS 3 - EXIT.
    ============================
    SEND SERVER >> 
    
        
    answered by 20.09.2017 / 18:50
    source