【问题标题】:How to create a class with a socket member如何使用套接字成员创建一个类
【发布时间】:2014-04-07 15:06:03
【问题描述】:

我创建了以下类,我想在其中包含一个套接字成员,然后想使用成员函数来连接、关闭、发送和接收。

class Connection:
  Kon = ""
  SSLx = ""
  def Close(self):
    try:
      self.Kon.close()
      return True
    except:
      return False

  def Send(self,Message):
    try:
      self.Kon.write(Message)
      return True
    except Exception,e:
      print e
      return False


  def Recieve(self):
    try:
      Response = self.Kon.recv(10240)
      return Response
    except:
      return False

#Conenct Function Makes a SSL connection with the node
  def Connect(self,Link):
    self.SSLx = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Ip = Link[0].replace("'",'')
    print Ip
    Port = int(Link[1])
    try:
      self.SSLx.connect((Ip,Port))
      return True
    except Exception,e:
      print "Connection Attempt Failed"
      self.Kon = socket.ssl(SSLx)
      return False

我成功运行了 .Connect 函数,但之后当我尝试发送函数时,它显示“str”对象没有写入成员。

关于如何完成这项工作的任何想法?

【问题讨论】:

  • 在您的 Connect() 方法中,您将套接字对象分配给 self.SSLx,但在您的 Send()/Receive() 方法中,您假设 self.Kon 是套接字。
  • 尝试一些修改。

标签: python sockets python-sockets


【解决方案1】:

我在调试过程中似乎出现了一个小错误,我将初始化 Kon 变量的行移到了下面几行。以下是修正后的类。

 class Connection:
  Kon = ""
  SSLx = ""
  def Close(self):
    try:
      self.Kon.close()
      return True
    except:
      return False

  def Send(self,Message):
    try:
      self.Kon.write(Message)
      return True
    except Exception,e:
      return False


  def Recieve(self):
    try:
      Response = self.Kon.read(10240)
      return Response
    except Exception,e:
      print e
      return False

#Conenct Function Makes a SSL connection with the node
  def Connect(self,Link):
    self.SSLx = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    Ip = Link[0].replace("'",'')
    print Ip
    Port = int(Link[1])
    try:
      self.SSLx.connect((Ip,Port)) 
      self.Kon = socket.ssl(self.SSLx)
      return True
    except Exception,e:
      print e
      print "Connection Attempt Failed"
      return False

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 2013-08-12
    • 1970-01-01
    • 2013-11-17
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多