create a server capable of serving multiple clients in python 3.6

0

At the moment my server can only serve a client with whom I can send text messages, I would like to connect with another client and do the same

#cliente
import socket

host = "127.0.0.1"
port = 6666

sock = socket.socket()

sock.connect((host, port))

datos = sock.recv(4096)
print (datos.decode('utf-8'))



while True:


  message = input("envia un mensaje")
  sock.send(message.encode('utf-8'))




  if message == "quit":
    break
    print("bye")
    sock.close()




#servidor
import socket

host = "127.0.0.1"
port = 6666

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Created")
sock.bind((host, port))
print ("socket bind complete")
sock.listen(1)
print ("socket now listening")

while 1:
        conn, addr = sock.accept()
        try:

             print('conexion con {}.'.format(addr))

             conn.send("server: Hello client".encode('UTF-8'))

             while True:

                 datos = conn.recv(4096)
                 if datos:
                     print('recibido: {}'.format(datos.decode('utf-8')))

                 else:
                     print("prueba")
                     break



        finally:
            conn.close()  
    
asked by steven 14.04.2017 в 23:18
source

1 answer

1

try the next server, you can improve it and do it to your liking, the only change there is the threading module.

#servidor
import socket
import threading

host = "127.0.0.1"
port = 6666

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Created")
sock.bind((host, port))
print ("socket bind complete")
sock.listen(1)
print ("socket now listening")


def worker(*args):
    conn = args[0]
    addr = args[1]
    try:
        print('conexion con {}.'.format(addr))
        conn.send("server: Hello client".encode('UTF-8'))
        while True:
            datos = conn.recv(4096)
            if datos:
                print('recibido: {}'.format(datos.decode('utf-8')))

            else:
                print("prueba")
                break
    finally:
        conn.close()

while 1:
    conn, addr = sock.accept()
    threading.Thread(target=worker, args=(conn, addr)).start()

Greetings

    
answered by 16.04.2017 в 11:55