如何使用socket memb创建类

2024-09-30 10:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了下面的类,我想在其中有一个套接字成员,然后想使用成员函数来连接、关闭、发送和接收。你知道吗

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函数,但在尝试Send函数之后,它会显示'str'对象没有写入成员。你知道吗

有没有什么办法?你知道吗


Tags: 函数selfipfalsetruereturndeflink
1条回答
网友
1楼 · 发布于 2024-09-30 10:32:58

在调试过程中似乎出现了一个小错误,我将初始化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

相关问题 更多 >

    热门问题