【发布时间】:2015-03-11 10:48:47
【问题描述】:
我有一个 django 应用程序,它需要与远程 TCP 服务器通信。该服务器将发送包,根据包是什么,我需要将条目添加到数据库并通知应用程序的其他部分。我还需要主动向 TCP 服务器发送请求,例如当用户导航到某个页面时,我想订阅 TCP 服务器上的某个流。所以双向沟通都需要进行。
到目前为止,我使用以下解决方案:
我写了一个自定义的 Django 命令,我可以从它开始
python manage.py listen
此命令将使用reactor.connectTCP(IP, PORT, factory) 启动一个扭曲的套接字服务器,并且由于它是一个 django 命令,我将可以访问数据库和我的应用程序的所有其他部分。
但是由于我还希望能够通过某个 django 视图触发向 TCP 服务器发送一些东西,所以我有一个额外的套接字服务器,它在我的扭曲应用程序中由 reactor.listenTCP(PORT, server_factory) 启动。
然后,我将在我的 django 应用程序中直接连接到这个服务器,在一个新线程中:
class MSocket:
def __init__(self):
self.stopped = False
self.socket = None
self.queue = []
self.process = start_new_thread(self.__connect__, ())
atexit.register(self.terminate)
def terminate(self):
self.stopped = True
try:
self.socket.close()
except:
pass
def __connect__(self):
if self.stopped:
return
attempts = 0
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True and not self.stopped:
try:
print "Connecting to Socket Server..."
self.socket.connect(("127.0.0.1", settings.SOCKET_PORT))
print "Connection Successful!"
for msg in self.queue:
self.socket.send(msg)
self.queue = []
break
except:
pause = min(int(round(1.2**attempts)), 30)
print "Connection Failed! Try again in " + str(pause) + " seconds."
sleep(pause)
attempts += 1
self.__loop__()
def __loop__(self):
if self.stopped:
return
while True and not self.stopped:
try:
data = self.socket.recv(1024)
except:
try:
self.socket.close()
except:
pass
break
if not data:
break
self.__connect__()
def send(self, msg):
try:
self.socket.send(msg)
return True
except:
self.queue.append(msg)
return False
m_socket = MSocket()
m_socket 然后将由主urls.py 导入,以便它以 django 开头。
所以我的设置看起来像这样:
发送到 TCP 服务器:
Django (connect:8001) -------> (listen:8001) Twisted (connect:4444) ------> (listen:4444) TCP-Server
从 TCP 服务器接收
TCP-Server (listen:4444) ------> (connect:4444) Twisted ---(direct access)---> Django
这一切似乎都是这样工作的,但我担心这不是一个很好的解决方案,因为我必须打开这个额外的 TCP 连接。所以我现在的问题是,是否可以优化设置(我确信可以)以及如何完成。
【问题讨论】: