associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

ClientSocketServer

Aplicação Cliente Servidor

Servidor

   1 # -*- coding: utf-8 -*-
   2 # vim:ts=4:sw=4:et:tw=120:sm
   3 #
   4 # =============================================
   5 # Trabalho de Redes de Computadores
   6 # CTDS Noite - Unibratec
   7 # =============================================
   8 
   9 # SERVER
  10 
  11 import sys
  12 import random
  13 import md5
  14 from SocketServer import ThreadingMixIn, TCPServer, StreamRequestHandler
  15 
  16 DEFAULT_HOST = ""
  17 DEFAULT_PORT = 3389
  18 BUF_SIZE = 1024
  19 
  20 class MessageHandler(StreamRequestHandler):
  21     def handle(self):
  22         print "waiting msg..."
  23         buf = []
  24         while True:
  25             char = self.rfile.read(1)
  26             if char == '\0':
  27                 break
  28             buf.append(char)
  29         msg = ''.join(buf)
  30         print "Recebi a mensagem:", msg
  31 
  32         md5_hex = md5.md5(msg).hexdigest()
  33         print "MD5 Hex:", md5_hex,
  34 
  35         self.wfile.write("%s\0" % (md5_hex))
  36         print "wrote."
  37 
  38 class WelcomeHandler(StreamRequestHandler):
  39     def handle(self):
  40         print "Recebi uma conexão de:", self.client_address
  41 
  42         random_port = random.randint(1025, 0xFFFF)
  43         print "Ouvindo mensagem na porta:", random_port
  44 
  45         message_socket = TCPServer((DEFAULT_HOST, random_port), MessageHandler)
  46         self.wfile.write("%s\0" %(str(random_port)))
  47 
  48         message_socket.handle_request()
  49 
  50 class MyServer(ThreadingMixIn, TCPServer):
  51     allow_reuse_address = 1
  52 
  53 def main():
  54     welcome_sock = MyServer((DEFAULT_HOST, DEFAULT_PORT), WelcomeHandler)
  55     print "Ouvindo a porta:", DEFAULT_PORT
  56     welcome_sock.serve_forever()
  57 
  58 if __name__ == '__main__':
  59     main()

Cliente

   1 # -*- coding: utf-8 -*-
   2 # vim:ts=4:sw=4:et:tw=120:sm
   3 #
   4 # =============================================
   5 # Trabalho de RDC
   6 # CTDS Noite - Unibratec
   7 # =============================================
   8 
   9 import sys
  10 import random
  11 import socket
  12 from Tkinter import *
  13 from Dialog import Dialog
  14 
  15 host = "localhost"
  16 DEFAULT_PORT = 3389
  17 BUF_SIZE = 1024
  18 
  19 def read_str(sock):
  20     buf = []
  21     while True:
  22         char = sock.recv(1)
  23         if char == '\0':
  24             break
  25         buf.append(char)
  26     return ''.join(buf)
  27 
  28 class MainFrame(Frame):
  29     def __init__(self, parent=None):
  30         Frame.__init__(self, parent)
  31         self.master.title("Cliente MD5")
  32         self.grid()
  33 
  34         self.welcome_socket = None
  35         self.message_socket = None
  36 
  37         self.server = StringVar()
  38         self.msg = StringVar()
  39         self.md5 = StringVar()
  40         self.msg_port = StringVar()
  41 
  42         self.server.set("localhost")
  43 
  44         Label(self, text="Servidor:").grid(row=1, sticky=W)
  45         Label(self, text="Mensagem:").grid(row=2, sticky=W)
  46         Label(self, text="MD5:").grid(row=3, sticky=W)
  47 
  48         Entry(self, textvariable=self.server).grid(row=1, column=1, sticky=W+E, columnspan=2)
  49         Entry(self, textvariable=self.msg).grid(row=2, column=1, sticky=W+E)
  50         Entry(self, textvariable=self.md5, state=DISABLED) \
  51              .grid(row=3, column=1, sticky=W+E, columnspan=2)
  52         Entry(self, textvariable=self.msg_port, state=DISABLED).grid(row=2, column=2, sticky=W+E)
  53 
  54         Button(self, text="Get Port", command=self.connect).grid(row=1,column=3,sticky=W+E)
  55         Button(self, text="Send", command=self.send).grid(row=2,column=3,sticky=W+E)
  56         Button(self, text="Quit", command=self.exit).grid(row=3,column=3,sticky=W+E)
  57 
  58     def connect(self):
  59         if self.welcome_socket:
  60             return
  61 
  62         try:
  63             self.welcome_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  64             self.welcome_socket.connect((self.server.get(), DEFAULT_PORT))
  65         except Exception, e:
  66             self.welcome_socket = None
  67             Dialog(self, title="Erro!", text="Servidor fora do ar!", \
  68                          bitmap='error', default=0, strings=('OK',))
  69             return
  70 
  71         self.msg_port.set(read_str(self.welcome_socket))
  72 
  73     def send(self):
  74         if not self.msg_port.get():
  75             Dialog(self, title="Erro!", text="Porta não definida", \
  76                          bitmap='error', default=0, strings=('OK',))
  77             return
  78 
  79         if self.message_socket is None:
  80             self.message_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  81             self.message_socket.connect((self.server.get(), int(self.msg_port.get())))
  82 
  83         self.message_socket.send("%s\0" % self.msg.get())
  84         md5 = read_str(self.message_socket)
  85         self.md5.set(md5)
  86 
  87         self.message_socket.close()
  88         self.message_socket = None
  89         self.welcome_socket = None
  90         self.msg_port.set("")
  91 
  92 
  93     def exit(self):
  94         if self.welcome_socket:
  95             self.welcome_socket.close()
  96         if self.message_socket:
  97             self.message_socket.close()
  98         self.quit()
  99 
 100 if __name__=="__main__":
 101     myapp = MainFrame()
 102     myapp.mainloop()