Know if client is connected to the server

-1

I have a client and a server connected through the socket module in python3, server side I know when the client connects, but on the client side I have no messages when the client connects and would like to have this information on the side of the client to make sure it has connected to the server, my code is as follows:

Client:

import socket

host='10.6.4.198 ' # Endereço IP do Servidor
port=4840# Porto de comunicação, deve ser acima de 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.connect((host, port))


while True:
    command = input ("Enter your command: ")
    if command =='EXIT':
        #Send EXIT request to other end
        s.send(str.encode(command))
        break
    elif command == 'KILL':
        #Send KILL command
        s.send(str.enconde(command))
        break
    s.send(str.encode(command))
    reply = s.recv(1024)
    print(reply.decode('utf-8'))

s.close()

Server:

import socket


host = '10.6.4.198 ' # Especifica o endereo IP do nosso Servidor
port = 4840 # Porto através do qual se ir realizar a comunicação, porto acima de 1024


stroredValue= "Yo, What's up?" # variável de armazenamento de dados, poderia ser um ficheiro de texto etc.





# Função configuraçãoo do nosso servidor para que possamos chamá-lo 
def setupServer():
    s= socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    # s= socket(dominio, tipo, protocolo)
    # AF_INET especifica que o dominio pretendido da Internet 
    # SOCK_STREAM  define o tipo pretendido e suportado pelo dominio AF_INET 
    print("Socket Created.")

    # Declaraçãoo de impressão do não funcionamento do socket
    try:
        s.bind((host, port)) # liga o nosso host e porto 
    except socket.error as msg:
        print (msg)
    print ("Socket bind complete.")
    return s
# Funçãoo configuraçãoo da conexão do nosso servidor
def setupConnection():
    s.listen(1)# Permite uma conexão de cada vez.Pode-se alterar o valor par as conexes pretendidas ao mesmo tempo.
    conn, address = s.accept()# Configuraçãoo de conexão e endereçoo e aceitando qualquer que seja a escuta 
    print(" Connected to : " + address[0] + ":" + str(address[1]))#Str(Address[1]) converte o endereço ip para string
    return conn# retorna o valor de conexãoo

def GET():# recupera esse valor armazenado que se especificou anteriormente
    reply = storedValue
    return reply


def REPEAT(dataMessage):
    reply = dataMessage[1]
    return reply



def dataTransfer(conn):
    #A big loop that sendsreceives data until told not to.
    while True:
        #Receive the data
        data = conn.recv(1024)# receive the data
        data = data.decode('utf-8')# descodificação dos dados recebidos em utf-8
        #Split the data such that you separate the command from the rest of the data.
        dataMessage = data.split(' ',1)
        command = dataMessage[0]
        if command =='GET'
            reply = GET()
        elif command == 'REPEAT'
            reply = REPEAT(dataMessage)
        elif command == 'EXIT':
            print("Our client has left us :(")
            break
        elif command == 'KILL':
            print("Our server is shutting down.")
            s.close()
            break
        else:
            reply = 'Unknow Command'
        conn.sendall(str.encode(reply))
        print("Data has been sent!!!!")
    conn.close()



s = setupServer()# chama a funçãoo setupServer

while True:
    try:
        conn=setupConnection()#obtém a conexao
        dataTransfer(conn)
    except:
        break

After entering the while inside it was like this, I already tested but it is giving me error:

try:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as s:
        s.settimeout(5)
        s.connect((host, port))
        print("Client1 connected to the Server")
        while True:
            command = input ("Enter your command: ")
            if command =='EXIT':
                #Send EXIT request to other end
                s.send(str.encode(command))
            break
            elif command == 'KILL':
                #Send KILL command
                s.send(str.enconde(command))
                break
            s.send(str.encode(command))
            reply = s.recv(1024)
            print(reply.decode('utf-8')
                  except socket.timeou as err:
                  print("Client1 isn't possible connected to the Server")
                  s.close()

The error it gives me is this:

File "cookieClientTrycatch.py", line 30
    elif command == 'KILL':
       ^
SyntaxError: invalid syntax

I have already executed the indentation in the code

Clients Connection:

Socket Created.
Socket bind complete.
Connected to : 192.168.1.100:58120

Second connected client does not appear

    
asked by anonymous 27.07.2018 / 13:32

1 answer

0

You can define a try / catch block to catch possible exceptions triggered by the socket module in case something goes wrong. For example, if a timeout occurs on the connection, the socket.timeout exception will be thrown.

For example:

try:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as s:

        # Aguarda no máximo 5 segundos pela conexão
        s.settimeout(5)

        # Tenta fazer a conexão com o servidor
        s.connect((host, port))

        # Tudo certo, prosseguir com o código...
        print('Parabéns! Você está conectado')

except socket.timeout as err:
    print('Não foi possível conectar ao servidor:', err)

Other exceptions can be triggered at different times in the module, so see the documentation and setting the code to your need.

    
27.07.2018 / 13:49