I have two TCP socket server in python, each with some (about 4) clients. I want the two server to be able to talk to each other so both can send commands to each other and communicate.
Is this possible? And if yes, how?
asked Oct 26, 2017 at 18:33
Michi Gruber
2543 silver badges19 bronze badges
-
yes of course you have just to make one of them client of the othersp________– sp________2017年10月26日 18:45:16 +00:00Commented Oct 26, 2017 at 18:45
-
I don't know what you really mean, but he will continue to serve his clients as wellsp________– sp________2017年10月26日 19:01:03 +00:00Commented Oct 26, 2017 at 19:01
-
I'm a bit confused right now, sorry, I'm new in programming. So how can I make a computer act like a client and as a server? Even if I try to use the same port it gives me an error...Michi Gruber– Michi Gruber2017年10月26日 19:02:59 +00:00Commented Oct 26, 2017 at 19:02
-
okay, I will post a complete answer with a brief example on how you can do thatsp________– sp________2017年10月26日 19:05:02 +00:00Commented Oct 26, 2017 at 19:05
-
1take a look at zeromq, all the network stuff will be abstracted from you and you can focus on your problemSedy Vlk– Sedy Vlk2017年10月26日 19:52:02 +00:00Commented Oct 26, 2017 at 19:52
1 Answer 1
This is an example:
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()
then with socket_between_servers the servers can communicate
answered Oct 26, 2017 at 19:51
sp________
2,64512 silver badges23 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Michi Gruber
thanks! i understand the concept now and will try to implement that
lang-py