我已经写了这两个.py代码来进行每个outher之间的通信。 A.py监听端口8888并将数据发送到7777 B.py监听端口7777并将数据发送到8888 这两个客户端部分在启动服务器后都陷入无限循环。 问题在哪里? 如果我只使用A.py中的服务器和B.py中使用的客户端(反之亦然),而没有使用任何线程,则它们工作正常。两个类之间的python线程无法正常工作
A.py:
import socket
import threading
import thread
import time
class server(threading.Thread):
s = ''
host = 0
port = 0
def __init__(self):
threading.Thread.__init__(self)
global s,host,port
s = socket.socket()
host = socket.gethostname()
port = 8888
def run(self):
global s,host,port
print 'Server started!'
print 'Waiting for clients...'
s.bind((host, port))
s.listen(5)
c, addr = s.accept()
print 'Got connection from', addr
while True:
time.sleep(2)
msg = c.recv(1024)
if len(msg)==0 : break
print addr, ' >> ', msg
class client(threading.Thread):
s = ''
host = 0
port = 0
def __init__(self):
threading.Thread.__init__(self)
global s,host,port
s = socket.socket()
host = socket.gethostname()
port = 7777
def run(self):
try:
time.sleep(5)
global s,host,port
print 'Connecting to ', host, port
s.connect((host, port))
print "Connectd"
while True:
time.sleep(2)
msg = raw_input('CLIENT >> ')
if len(msg)==0:break
s.send(msg)
except:
print "Waiting"
self.run()
thread1 = server()
thread2 = client();
thread1.start()
thread2.start()
thread1.join()
thread2.join();
B.py:
import socket
import threading
import thread
import time
class server(threading.Thread):
s = ''
host = 0
port = 0
def __init__(self):
threading.Thread.__init__(self)
global s,host,port
s = socket.socket()
host = socket.gethostname()
port = 7777
def run(self):
global s,host,port
print 'Server started!'
print 'Waiting for clients...'
s.bind((host, port))
s.listen(5)
c, addr = s.accept()
print 'Got connection from', addr
while True:
time.sleep(2)
msg = c.recv(1024)
if len(msg)==0 : break
print addr, ' >> ', msg
class client(threading.Thread):
s = ''
host = 0
port = 0
def __init__(self):
threading.Thread.__init__(self)
global s,host,port
s = socket.socket()
host = socket.gethostname()
port = 8888
def run(self):
try:
time.sleep(5)
global s,host,port
print 'Connecting to ', host, port
s.connect((host, port))
print "connected"
while True:
time.sleep(2)
msg = raw_input('CLIENT >> ')
if len(msg)==0:break
s.send(msg)
except:
print "waiting"
self.run();
thread1 = server()
thread2 = client();
thread1.start()
thread2.start()
thread1.join()
thread2.join();
哪里有客户端部分运行呢? – Sid 2012-02-06 18:57:52