Advertisement
diegomrodrigues

Python - Servidor TCP Concorrente

Jan 11th, 2018
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Exemplo de um Servidor TCP Concorrente (Multithread)
  4.  
  5. Artigo: https://www.linkedin.com/pulse/python-sockets-criando-um-servidor-tcp-concorrente-diego/
  6.  
  7. Diego Mendes Rodrigues
  8. '''
  9.  
  10. import socket
  11. import _thread
  12.  
  13. HOST = '127.0.0.1'      # Endereco IP do Servidor
  14. PORT = 5000             # Porta que o Servidor está
  15.  
  16. # Função chamada quando uma nova thread for iniciada
  17. def conectado(con, cliente):
  18.     print('\nCliente conectado:', cliente)
  19.  
  20.     while True:
  21.         # Recebendo as mensagens através da conexão
  22.         msg = con.recv(1024)
  23.         if not msg:
  24.             break
  25.  
  26.         print('\nCliente..:', cliente)
  27.         print('Mensagem.:', msg)
  28.  
  29.     print('\nFinalizando conexao do cliente', cliente)
  30.     con.close()
  31.     _thread.exit()
  32.  
  33. tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  34. orig = (HOST, PORT)
  35.  
  36. # Colocando um endereço IP e uma porta no Socket
  37. tcp.bind(orig)
  38.  
  39. # Colocando o Socket em modo passivo
  40. tcp.listen(1)
  41. print('\nServidor TCP concorrente iniciado no IP', HOST, 'na porta', PORT)
  42.  
  43. while True:
  44.     # Aceitando uma nova conexão
  45.     con, cliente = tcp.accept()
  46.     print('\nNova thread iniciada para essa conexão')
  47.  
  48.     # Abrindo uma thread para a conexão
  49.     _thread.start_new_thread(conectado, tuple([con, cliente]))
  50.  
  51. # Fechando a conexão com o Socket
  52. tcp.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement