Home | Mirror | Search | 杂文 | ITEYE 博客 | OSChina 博客 | 51CTO 博客 | Linkedin

9.4. Socket

9.4.1. UDP UDP Server

import asyncore, socket 

class AsyncoreServerUDP(asyncore.dispatcher): 
   def __init__(self): 

      # Bind to port 5005 on all interfaces 
      self.create_socket(socket.AF_INET, socket.SOCK_DGRAM) 
      self.bind(('', 5005)) 

   # Even though UDP is connectionless this is called when it binds to a port 
   def handle_connect(self): 
      print "Server Started..." 

   # This is called everytime there is something to read 
   def handle_read(self): 
      data, addr = self.recvfrom(2048) 
      print str(addr)+" >> "+data 

   # This is called all the time and causes errors if you leave it out. 
   def handle_write(self): 

asyncore.loop() UDP Clinet

import socket, asyncore 

class AsyncoreClientUDP(asyncore.dispatcher): 

   def __init__(self, server, port): 
      self.server = server 
      self.port = port 
      self.buffer = "" 

      # Network Connection Magic! 
      self.create_socket(socket.AF_INET, socket.SOCK_DGRAM) 
      self.bind( ('', 0) ) # bind to all interfaces and a "random" free port. 
      print "Connecting..." 

   # Once a "connection" is made do this stuff. 
   def handle_connect(self): 
      print "Connected" 
   # If a "connection" is closed do this stuff. 
   def handle_close(self): 

   # If a message has arrived, process it. 
   def handle_read(self): 
      data, addr = self.recv(2048) 
      print data 

   # Actually sends the message if there was something in the buffer. 
   def handle_write(self): 
      if self.buffer != "": 
         print self.buffer 
         sent = self.sendto(self.buffer, (self.server, self.port)) 
         self.buffer = self.buffer[sent:] 

connection = AsyncoreClientUDP("",5005) # create the "connection" 
while 1: 
   asyncore.loop(count = 10) # Check for upto 10 packets this call? 
   connection.buffer += raw_input(" Chat > ") # raw_input (this is a blocking call)
comments powered by Disqus