TCP threaded python
<p>I'm learning some Networking through Python and came up with this idea of TCPServer Multithread so i can have multiple clients connected. The problem is that i can only connect one client.</p>

<pre><code>import socket
import os
import threading
from time import sleep
from threading import Thread

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Preparado...')

def Main():
host = '127.0.0.1'
port = 5000

s.bind((host, port))
print('Enlaze listo...')

print('Escuchando...')
s.listen(5)
c, addr, = s.accept()
os.system('cls')

print('Conexion desde: '+str(addr))

def handle_client(client_socket):
while True:
    data = client_socket.recv(1024).decode('utf-8')
    if not data: break
    print('Client says: ' + data)
    print('Sending: ' + data)
    client_socket.send(data.encode('utf-8'))
client_socket.close()

if __name__ == '__main__':
while True:
    Main()
    client_socket, addr = s.accept()
    os.system('cls')
    print('Conexion desde: '+str(addr))
    Thread.start_new_thread(handle_client ,(client_socket,))
s.close()
</code></pre>

<p>Edit: This is my actual code, to test it i open up two Client.py codes and try to connect to it. The first Client.py successfully connects (Although there's bugs in receiving and sending back info)The second one executes but it's not shown in the server output as connected or something, it just compiles and stays like that.</p>

<p>Ok, here's the code solved, i should have said i was working on Python3 version. Reading the docs i found out, here's the code and below the docs.</p>

<pre><code>import socket
import os
import threading
from time import sleep
from threading import Thread
import _thread

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Preparado...')

def Main():
host = '127.0.0.1'
port = 5000

s.bind((host, port))
print('Enlaze listo...')

print('Escuchando...')
s.listen(1)





def handle_client(client_socket):
while True:
    data = client_socket.recv(1024).decode('utf-8')
    if not data: break
    print('Client says: ' + data)
    print('Sending: ' + data)
    client_socket.send(data.encode('utf-8'))
client_socket.close()

if __name__ == '__main__':
Main()
while True:

    client_socket, addr = s.accept()
    os.system('cls')
    print('Conexion desde: '+str(addr))           
    _thread.start_new_thread(handle_client ,(client_socket,))
s.close()
</code></pre>

<p><a href="https://docs.python.org/3/library/threading.html" rel="nofollow">https://docs.python.org/3/library/threading.html</a>
<a href="http://www.tutorialspoint.com/python3/python_multithreading.htm" rel="nofollow">http://www.tutorialspoint.com/python3/python_multithreading.htm</a></p>

<p>The problem was at <code>_thread.start_new_thread(handle_client ,(client_socket,))</code> just <code>import _thread</code> ask some questions here, keep researching and got it. </p>

<p>Thanks all of you.</p>

<p>WhiteGlove    </p>

python multithreading sockets networking tcp