Socket in python

Asked

Viewed 545 times

1

I’m doing the discipline of networks and computers and I’m having trouble on the following question:

Using TCP, deploy a server that offers two features: uppercase and Daytime. The client, when sending a message to the server, should receive as a response the message in uppercase letters and the time the server received its request.

Well, I’m having trouble using the function upper() on the server. below is my code.

Tcpserver.py

from socket import *  

serverPort = 3000

serverSocket = socket(AF_INET, SOCK_STREAM)

#atribui a porta ao socket criado
serverSocket.bind(('', serverPort))    

#aceita conexões com no máximo um cliente na fila 
serverSocket.listen(1)

print('The server is ready to receive')


while True:
    connectionSocket, addr = serverSocket.accept()         

    #recebe a mensagem do cliente em bytes
    mensagem = connectionSocket.recv(1024)     



    #envio tbm deve ser em bytes
    mensagem = mensagem.upper()
    connectionSocket.send(mensagem)

    connectionSocket.close()

Tcpclient.py

from socket import *   

serverName = 'localhost'

mensagem = "gustavo"

serverPort = 3000


clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName, serverPort))


#a mensagem deve estar em bytes antes de ser enviada ao buffer de transmissão
clientSocket.send(mensagem.encode())


#recebe a resposta do servidor
clientSocket.recv(1024)

#devemos converter a mensagem de volta para string antes de imprimí-la
print('Resposta:' , mensagem)

#fecha a conexão
clientSocket.close()

Well, what’s going on in my code, you must be wondering! well, it connects the server normally and the client output is not uppercase.

I would like help using UPPERCASE on the TCP server.

1 answer

1


On line 20 where the clientSocket.recv(1024), you did not pass the answer to the variable mensagem. So what was printed was the message you sent and not the one you received.

I know it’s not related to your question, but don’t forget to decode the string when receiving it from the method recv, otherwise you may get several errors in your code.

Correct client code:

from socket import *   

serverName = 'localhost'

mensagem = "gustavo"

serverPort = 3000


clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect((serverName, serverPort))


#a mensagem deve estar em bytes antes de ser enviada ao buffer de transmissão
clientSocket.send(mensagem.encode())


#recebe a resposta do servidor
msg = clientSocket.recv(1024).decode()

#devemos converter a mensagem de volta para string antes de imprimí-la
print('Resposta:' , msg)

#fecha a conexão
clientSocket.close()

Browser other questions tagged

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