我想在 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