获取线程。定义为变量时传递目标类对象

时间:2016-03-06 00:52:32

标签: python multithreading python-2.7 sockets

我试图理解网络的基础知识,我相信开始学习基本服务器处理的正确方法是通过套接字。

  1. 我知道有更好的库,如twisted或socketServer。我想在socket模块中专门做。
  2. 我知道使用套接字模块构建服务器是不可靠的。
  3. 我也知道我需要实施某种协议以供将来使用。
  4. 我尝试使用threading构建P2pClient.Thread继承:

    ctx.fillStyle = "grey";
    ctx.beginPath();
    ctx.rect(100, 100, 50, 50);
    ctx.rect(400, 0, -400, 400);
    ctx.fill();
    

    但是当输入为" connect localhost:

    时,最终会出现以下错误
    import socket
    import threading
    
    
    class P2pServer(threading.Thread):
        def __init__(self, host, port):
            threading.Thread.__init__(self)
            print "Info: %s:%s" % (host, port)
            self.server = socket.socket()
            self.server.bind((host, port))
            print "Created the server"
            self.server.listen(1)  # p2p chat
    
        def run(self):
            while True:
                c, addr = self.server.accept()
                print "Connected from %s (%s)" % (addr, c)
    
    
    class P2pClient(threading.Thread):
        def __init__(self, host, port):
            threading.Thread.__init__(self, host, port)
            self.client = socket.socket()
            self.client.connect((host, port))
    
        def send_msg(self, msg):
            try:
                self.client.send(msg)
                return "Sent: %s" % msg
            except socket.error as e:
                return "Could not send because  of %s" % e
    
        def run(self):
            while True:
                recv = self.client.recv(1024)
                if len(recv) > 0:
                    print recv
    
    server = P2pServer("localhost", 44444) # This is our server
    server.start() # Run it
    client = None
    
    print "Ready to take input"
    while True:
        print "Your command: ",
        cmd = raw_input()
        if cmd.startswith("connect "):
            cmd = cmd.split()
            client = P2pClient(cmd[1], cmd[2])
            client.start()
        else:
            client.send_msg(cmd)
    

    网站上的解决方案建议将其设置为直接使用threading.Thread()函数,而不是以前一种方式执行。但是,线程文档并没有给我一个关于如何达到目标函数的想法。如何构建允许我在客户端变量中访问P2pClient的线程?

    以下代码的目的是使它在同一主机中的两个不同端口运行,在两个服务器之间建立P2P连接。

    Traceback (most recent call last):
      File "C:/Users/edız/Desktop/Ediz/Python/Playground/servers test/p2p.py", line 49, in <module>
        client = P2pClient(cmd[1], cmd[2])
      File "C:/Users/edız/Desktop/Ediz/Python/Playground/servers test/p2p.py", line 22, in __init__
        threading.Thread.__init__(self, host, port)
      File "C:\Python27\lib\threading.py", line 670, in __init__
        assert group is None, "group argument must be None for now"
    AssertionError: group argument must be None for now
    

1 个答案:

答案 0 :(得分:0)

你的第一个例子很接近。问题是您将子P2pClient所需的额外参数传递给父Thread类。 thread采用不同的参数集。在初始化父项时,请保留这些参数。

class P2pClient(threading.Thread):
    def __init__(self, host, port):
        threading.Thread.__init__(self)
        self.client = socket.socket()
        self.client.connect((host, port))