1

我想在 Python 上制作一个聊天程序,这样我就可以发送和接收数据。
我在想我可以运行多个线程,每个线程用于客户端和服务器。
我的问题是
如何在一个文件中为两个类运行多个线程?

我当前的代码:

from socket import *
from threading import Thread

class Server(Thread):
    def __init__(self,host,port,user):
        self.port = port
        self.host = host
        self.user = user
        self.bufsize = 1024
        self.addr = (host,port)

        self.socket = socket(AF_INET , SOCK_STREAM)
        self.socket.bind(self.addr)
        Thread.__init__(self)

    def run(self):
        self.socket.listen(5)
        while True:
            print 'Waiting for connection..'
            client, caddr = self.socket.accept()
            print 'Connected To',caddr

            data = client.recv(self.bufsize)
            if not data:
                continue
            print data         


class Client(Thread):
    def __init__(self,host,port,user):
        self.port = port
        self.host = host
        self.user = user
        self.bufsize = 1024
        self.addr = (host,port)

        self.socket = socket(AF_INET , SOCK_STREAM)
        Thread.__init__(self)

    def run(self):
        self.socket.connect(self.addr)
        while True:
            data = raw_input('> ')
            if not data:
                continue
            data = user+' said : '+data
            tcpClient.send(data)

host = ''
p1 = int(raw_input('Enter Port 1 : '))
p2 = int(raw_input('Enter Port 2 : '))
user = raw_input('Enter Your user: ').strip()

client = Client(host,p1,user)
server = Server(host,p2,user)

client.start()
server.start()

我当前的错误消息:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python2.7 For Chintoo\lib\threading.py", line 552, in __bootstrap_inner
    self.run()
  File "C:\Users\karuna\Desktop\Jython\Python\My Modules\Network\Chat.py", line 41, in run
    self.socket.connect(self.addr)
  File "C:\Python2.7 For Chintoo\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10049] The requested address is not valid in its context
4

2 回答 2

2

线程模块应该正是您所需要的。http://docs.python.org/2/library/threading.html

from socket import *
from threading import Thread

class Server(Thread):
    def __init__(self,host,port,name):
        Thread.__init__(self)
        self.port = port
        self.host = host
        self.name = name
        self.bufsize = 1024
        self.addr = (host,port)

        self.socket = socket(AF_INET , SOCK_STREAM)
        self.socket.bind(self.addr)

    def run(self):
        self.socket.listen(5)
        while True:
            print 'Waiting for connection..'
            client, caddr = self.socket.accept()
            print 'Connected To',caddr

            data = client.recv(self.bufsize)
            if not data:
                continue
            print data         


class Client(Thread):
    def __init__(self,host,port,name):
        Thread.__init__(self)
        self.port = port
        self.host = host
        self.name = name
        self.bufsize = 1024
        self.addr = (host,port)

        self.socket = socket(AF_INET , SOCK_STREAM)

    def run(self):
        invalid = True
        while invalid:
            try:
                invalid = False
                self.socket.connect(self.addr)
            except:
                invalid = True

        while True:
            data = raw_input('> ')
            if not data:
                continue
            data = name+' said : '+data
            tcpClient.send(data)

host = ''
p1 = int(raw_input('Enter Port 1 : '))
p2 = int(raw_input('Enter Port 2 : '))
name = raw_input('Enter Your Name: ').strip()


server = Server(host,p2,name)
client = Client(host,p1,name)

server.start()
client.start()

server.join()

同样由于某些原因,如果您创建简单的类,则不应在 python 中使用旧样式类,并且至少从这样的对象继承

类的东西(对象):....

于 2013-02-15T12:43:36.190 回答
0

好吧,只需启动多个线程:

from threading import Thread

class Foo(Thread):
     def __init__(self):
         Thread.__init__(self)
         self.keepRunning = True
     def run(self):
         while self.keepRunning:
            print "running in thread", self

import time
if __name__ == "__main__":
     mythread1 = Foo()
     mythread2 = Foo()
     mythread1.start()
     mythread2.start()
     time.sleep(10) # and let the 2 threads to their work
     mythread1.keepRunning = False
     mythread2.keepRunning = False
于 2013-02-15T12:39:39.447 回答