-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
Sergio, now the error you presented is syntax. See that in the previous line of
elif
thebreak
is not indented correctly. Please pay more attention when writing your code and especially review it several times before asking.– Woss