Know if client is connected to the server

Asked

Viewed 477 times

-2

I have a client and a server connected through the socket module in python3, on the server side I know when the client is connected, but on the client side I have no message when the client connects and I would like to have this client-side information to make sure that it 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 inserting the while in got like this, I have 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 mistake he gives me is this:

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

I already executed the indentation in the code

Connection of Clients:

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

the second connected client does not appear

  • 1

    Sergio, now the error you presented is syntax. See that in the previous line of elif the break is not indented correctly. Please pay more attention when writing your code and especially review it several times before asking.

1 answer

0

You can define a block Try/catch to capture possible exceptions triggered by the module socket if something goes wrong. For example, if a timeout in connection, the exception socket.timeout will be fired.

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 of the module, so see documentation and adjust the code to your need.

  • before the while True?

  • @Sergionunes the loop should go inside the with

  • edited my question with the loop inside the with

  • @Sergionunes commenting "gave error" does not help anything if you do not say the error. You know how it works the with? If not, read on What’s with no Python for?

  • I got connectivity, however with two connected clients only appears the first connected ip, as I can make appear do the second, as I posted above in the question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.