Guest User

Localchat chatclient Python source

a guest
Mar 31st, 2012
55
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python2.6
  2. """Frack Open Dag 2012 - Demonstratie chat client."""
  3. __author__ = 'Elmer de Looff <elmer@underdark.nl>'
  4. __version__ = '0.1'
  5.  
  6. # Standard modules
  7. import datetime
  8. import gtk
  9. import os
  10. import socket
  11. import threading
  12.  
  13. PORT = 50001
  14.  
  15.  
  16. class Localchat(object):
  17.   def __init__(self):
  18.     """Initializes the Localchat class.
  19.  
  20.    The quotes are read and stored, and the GUI is built after that.
  21.    """
  22.     self.last_message = 0
  23.     self.username = None
  24.     self.server = None
  25.     # Set up the socket to use for writing
  26.     self.sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  27.     self.sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  28.     # Set up the socket used for receiving
  29.     Receiver(self.AddMessage)
  30.     # Start application, spawn windows
  31.     self._MainWindow()
  32.     self._ConfigureName()
  33.  
  34.     # Start the main GTK loop. This is required.
  35.     # This call will NOT return, any code beyond this point is inaccessible.
  36.     self._Main()
  37.  
  38.   def _MainWindow(self):
  39.     """Builds the GUI and opens the main window."""
  40.     # Initiate a GTK Builder from which the GUI will be built
  41.     self.builder = gtk.Builder()
  42.     # Load the `client.glade` file which holds the GUI configuration. This
  43.     # particular construct loads the file from the exact same directory this
  44.     # file is in, regardless of the diretory from which the file is called.
  45.     self.builder.add_from_file(os.path.join(
  46.         os.path.dirname(__file__), 'client.glade'))
  47.     # Connecting the signals triggered by events (buttons etc) to the methods
  48.     # of the Localchat class.
  49.     self.builder.connect_signals(self)
  50.     # Grab the object `localchat` (this is the main window) and make it visible.
  51.     self.builder.get_object('localchat').show()
  52.  
  53.   def _ConfigureName(self, *_args):
  54.     settings = self.builder.get_object('settings')
  55.     settings.connect('delete-event', settings.hide_on_delete)
  56.     settings.show()
  57.  
  58.   @staticmethod
  59.   def _Exit(*_args):
  60.     """Gracefully exit the application."""
  61.     raise SystemExit
  62.  
  63.   def _Main(self):
  64.     # Start threaded operation and start the GTK main loop.
  65.     # to user actions on the GUI.
  66.     gtk.gdk.threads_init()
  67.     gtk.main()
  68.  
  69.   def GetMessages(self, *_args):
  70.     """This outputs a random quote to the display box."""
  71.     # `random.choice` grabs a random item from a list of items.
  72.     message_url = '%s/json/from/%s' % (self.server, self.last_message)
  73.     messages = urllib2.urlopen(message_url).read()
  74.     for message in cjson.decode(messages):
  75.       self.AddMessage(message)
  76.  
  77.   def AddMessage(self, message):
  78.     now = datetime.datetime.now()
  79.     label = gtk.Label('%s %s' % (now.strftime('%H:%M'), message))
  80.     msg_vbox = self.builder.get_object('messages')
  81.     msg_vbox.pack_start(label, False, False)
  82.     label.set_alignment(0, 0)
  83.     label.set_line_wrap(True)
  84.     label.show()
  85.  
  86.   def _SendMessage(self, *_args):
  87.     message = self.builder.get_object('input_message').get_text()
  88.     self.builder.get_object('input_message').set_text('')
  89.     self.SendMessage('<%s> %s' % (self.username, message))
  90.  
  91.   def SendMessage(self, message):
  92.     self.sender.sendto(message, ('<broadcast>', PORT))
  93.  
  94.   def SaveSettings(self, *_args):
  95.     self.username = self.builder.get_object('input_username').get_text()
  96.     self.builder.get_object('settings').hide()
  97.     self.SendMessage('* %s joined the chat' % self.username)
  98.  
  99.  
  100. class Receiver(threading.Thread):
  101.   def __init__(self, callback):
  102.     super(Receiver, self).__init__(name='Receiver')
  103.     self.daemon = True
  104.     self.callback = callback
  105.     self.start()
  106.  
  107.   def run(self):
  108.     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  109.     sock.settimeout(0.1)
  110.     sock.bind(('', PORT))
  111.     while True:
  112.       try:
  113.         self.callback(sock.recv(65536))
  114.       except socket.error:
  115.         pass
  116.  
  117.  
  118. def main():
  119.   Localchat()
  120.  
  121.  
  122. if __name__ == '__main__':
  123.   main()
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×