我在python中有两个TCP套接字服务器,每个服务器都有一些(大约4个)客户端。我希望两台服务器能够相互通信,这样两者都可以互相发送命令并进行通信。
这可能吗?如果是的话,怎么样?
答案 0 :(得分:1)
这是一个例子:
import socket
socket_between_servers = None
def connect_to(host='', port=1060):
global socket_between_servers
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port)) #check if the first server is already waiting
socket_between_servers = sock
except socket.error:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(5) # waiting for the 4 clients plus the other server
print 'waiting for the peers...'
n = 0
while n < 5:
sc, sockname = s.accept()
if sockname == 'ip addresse of the other server':
socket_between_servers = sc
n += 1
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port + 1))
s.listen(4) # waiting for the 4 clients
n = 0
while n < 4:
sc, sockname = s.accept()
然后使用socket_between_servers
服务器可以进行通信