返回介绍

9.5. Socket

发布于 2024-02-10 15:26:30 字数 2183 浏览 0 评论 0 收藏 0

9.5. Socket

9.5.1. UDP

9.5.1.1. UDP Server

import asyncore, socket 

class AsyncoreServerUDP(asyncore.dispatcher): 
   def __init__(self): 
      asyncore.dispatcher.__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): 
      pass 

AsyncoreServerUDP() 
asyncore.loop()

9.5.1.2. UDP Clinet

import socket, asyncore 

class AsyncoreClientUDP(asyncore.dispatcher): 

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

      # Network Connection Magic! 
      asyncore.dispatcher.__init__(self) 
      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): 
      self.close() 

   # 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("127.0.0.1",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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文