Code review: Threaded server to handle multiple clients

Asked

Viewed 68 times

1

The server with Threading:

import socket

from threading import Thread



def Servidor():

    servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    ip = "0.0.0.0"
    porta = 8884

    servidor.bind((ip, porta))

    servidor.listen(5)



    while True:
        socket_client, adddress = servidor.accept()

        dados = socket_client.recv(2048)

        print("Cliente: ", dados.decode("utf8"))
        msg = input("Servidor: ")
        enviados = socket_client.send(msg.encode("utf8"))

    servidor.close()



MeuServidor = Thread(target=Servidor,args=[])

MeuServidor.start()

the client:

import socket

ip ="localhost"
porta = 8884

cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

cliente.connect((ip,porta))


while True:

    msg = input("Cliente: ")
    cliente.send(msg.encode("utf8"))
   # print("Cliente: ", msg)
    recebido = cliente.recv(1024)
    print("Servidor: ", recebido.decode("utf8"))

cliente.close()

What’s happening: The server only accepts a single client!

1 answer

4

The server logic should be like this:

Enquanto verdadeiro:
    Accept (operação bloqueante)
    Criar uma nova Thread e passar para ela o socket_client. Ela deverá ficar em loop tratando a chegada de mensagens até receber ordem de fechar
Fim enquanto
  • What’s wrong with my code? Something’s missing?

  • Your code is not creating a Thread for each socket_client created on each Accept.

  • Could you fix it? I’ve been trying to fix it for a long time!

  • Now you got me! I don’t know too much of Python hahahah... someone should fix it otherwise after I try an answer

  • I have heard that the threading module is not good. I should use another module!

  • Thanks! I’m still learning. Someone fix helps me in learning!

Show 1 more comment

Browser other questions tagged

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