Multi-thread Imperative programming and sockets

1

I know the threads at the theoretical level, I know there are two modules to use them, one is low level and the other high level, the first is threading and the second is thread, this I have seen in a wiki, after that I know that there are many methods but I do not know what to use for my purpose, I mean a local chat that can serve multiple clients, what I have now is a server that can only serve one client, if I connect with another client close the connection, the code is as follows I inform that I do not master object oriented programming very well therefore I appreciate that the solution is according to this style.

#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()



#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()
    
asked by steven 15.04.2017 в 14:10
source

1 answer

0

To create a multi-threaded server, you have to pass incoming connections to threads. This way the server can continue accepting new connections while the client communicates in the new thread. In this question in English code for a simple server is found in the response of nettux443 .

This example is simplified because it is not completely asynchronous, each connection still works in a sequential dialog. The main thing is to move the blocking method ( .recv(size) ) in a separate thread.

import socket
import threading

class ThreadedServer(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):
        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            client.settimeout(60)
            threading.Thread(target = self.listenToClient,args = (client,address)).start()

    def listenToClient(self, client, address):
        size = 1024
        while True:
            try:
                data = client.recv(size)
                if data:
                    # servidor espejo: se devuelve la misma información que 
                    # el cliente envió 
                    response = data
                    client.send(response)
                else:
                    raise error('Cliente desconectado')
            except:
                client.close()
                return False

if __name__ == "__main__":
    port_num = input("Puerto? ")
    ThreadedServer('',port_num).listen()

The listen method creates the socket that listens to incoming connections. After accepting a connection, call listenToClient in a new thread to immediately continue receiving more connections, while the new thread handles the connection to the client.

Within the thread of a particular connection, this example waits for incoming data, responding with an exact copy of the received data (mirror server) and then returning to expect more data. This procedure is repeated until except comes out due to connection interruption (for example, because the client closed the connection).

For a chat you have to pass the incoming data to the message window and you have to implement an access to the connection to send messages outside the thread that listens.

    
answered by 15.04.2017 в 14:49