开发者

Spawning a QThread containing a socket connection in python

I am currently trying implement a QThread that contains a socket connection. The socket connection runs repeatedly (while 1:) checking for new data received. Once this data is received, it is supposed to fire off a SIGNAL calling a开发者_运维知识库 function and feeding it the received data.

I got the socket connection working. When I run the function on its own it waits for data and prints whenever new data comes in. However since I am trying to build a GUI with Qt I have to put this in its own thread so it allows the app to continue functioning.

So to thread it I implemented a GenericThread class that takes any function and runs it inside a thread. My MainWindow class connects the sockets SIGNAL, instantiates a GenericThread and then starts it. This however causes my app to hang. Below are the relevant pieces of code:

The socket connection

def remoteConn(self, HOST='my.server', PORT=25562):
  import socket
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect((HOST, PORT))
  newLinesRaw = ''
  while 1:
    newData = s.recv(1024)
    if newData:
      print '<rawData>\n', newData, '\n</newData>\n'
      newLinesRaw += newData
    else:
      if newLinesRaw:
        newLines = newLinesRaw.split('\n')
        print '\nNew Lines:\n', newLines
        self.emit(QtCore.SIGNAL('newRemoteLines'), newLines)
        newLinesRaw=''
      else:
        time.sleep(.1)
  s.close()

The generic thread class

class GenericThread(QtCore.QThread):
  def __init__(self, function, *args, **kwargs):
    QtCore.QThread.__init__(self)
    self.function = function
    self.args = args
    self.kwargs = kwargs

  def __del__(self):
    self.wait()

  def run(self):
    if self.args and self.kwargs:
      self.function(*self.args,**self.kwargs)
    elif self.args and not self.kwargs:
      self.function(*self.args)
    elif not self.args and self.kwargs:
      self.function(**self.kwargs)
    else:
      self.function()
    return

Spawning the remote thread. Note that both print statements are executed.

  print 'spawning remote thread'
  self.connect(self, QtCore.SIGNAL('newRemoteLines'), self.routeServerLines)
  thread = GenericThread(self.remoteConn)
  thread.start()
  print 'thread started'

I am new to sockets and threading so I may be making a very stupid error somewhere.


The thread might be destroyed if there is no further reference to it.

Try using self.thread instead of just thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜