0

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
5
  • yes of course you have just to make one of them client of the other Commented Oct 26, 2017 at 18:45
  • I don't know what you really mean, but he will continue to serve his clients as well Commented 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... Commented Oct 26, 2017 at 19:02
  • okay, I will post a complete answer with a brief example on how you can do that Commented Oct 26, 2017 at 19:05
  • 1
    take a look at zeromq, all the network stuff will be abstracted from you and you can focus on your problem Commented Oct 26, 2017 at 19:52

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! i understand the concept now and will try to implement that

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.