#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    12
    Rep Power
    0

    Communicating with multiple clients using one TCP socket


    I am using TCP sockets to communicate between my server and clients. The server code and socket code are as below:

    server:

    Code:
    from socket import *
    
    HOST = 'xx.xx.xx.xx'
    PORT = 1999
    serversocket = socket(AF_INET,SOCK_STREAM)
    serversocket.bind((HOST,PORT))
    print 'bind success'
    serversocket.listen(5)
    print 'listening'
    while True:
        (clientsocket, address) = serversocket.accept()
        print ("Got client request from",address)
        #clientsocket.send('True')
        data = clientsocket.recv(1024)
        print data
        clientsocket.send('True')
        clientsocket.close()
    client:
    Code:
    import socket
    import sys
    
    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # Connect the socket to the port on the server given by the caller
    server_address = ('xx.xx.xx.xx', 1999)
    print >>sys.stderr, 'connecting to %s port %s' % server_address
    sock.connect(server_address)
    
    try:
    
        message = 'This is the message.  It will be repeated.'
        print >>sys.stderr, 'sending' 
        for x in range (0,1):
          name=raw_input ('what is ur name')
          print type(name)
          sock.send(name)
          print sock.recv(1024)
    
    finally:
        sock.close()
    I am able to communicate with the server from client and able to send and receive data. But the problem I am facing is that I am not able to send and receive data continuously from the server. I have to restart my client code on my laptop to send and receive data again from the server. The way the above client code is working is that when I give a keyboard input, then the socket sends data to server and server responds back. But in the client code, in the for loop if I do two iterations, for the second iteration the data I enter from keyboard is not reaching server. I need to restart my client code to send data again. How do I fix this ?

    Also, when once client is connected to the server, the other cannot connect to the server. Any ideas on how to do this ?
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,805
    Rep Power
    508
    I'm quite sure there are people who respond on the c language forum who can solve your issue. See if you can disguise your question as a c question and post there. I suspect this is a network issue rather than specific language problem.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Not An Expert
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2015
    Posts
    404
    Rep Power
    3
    I could move this topic to that section, if that would help?
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    12
    Rep Power
    0
    Originally Posted by markroberts
    I could move this topic to that section, if that would help?
    sure
  8. #5
  9. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,323
    Rep Power
    2226
    Assuming I'm interpreting that pseudo-code correctly.

    Client question first. Try placing the send/recv code in a loop that needs a specific condition to exit. For example, an echo client could go into an infinite loop the prompts the user for an input string to send and does that over and over again until the user enters a special input (eg, an empty string created by just hitting the Enter key) which caused it to drop out of that loop.

    Server question. Sockets block. While you're waiting for input from one socket, your program freezes making you unable to check any other client socket or even the listening socket. I discuss the problem and techniques in C for dealing with it: Dealing With and Getting Around Blocking Sockets.

    Hope that helped.
  10. #6
  11. No Profile Picture
    Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2003
    Location
    Anaheim, CA (USA)
    Posts
    6,649
    Rep Power
    2479
    Originally Posted by bobdxcool
    [...] I need to restart my client code to send data again. How do I fix this ?
    Your range() call appears to be wrong. Remember that range(START, STOP) will stop at the largest number strictly less than STOP. So in order to stop at 1 (to have the two items 0 and 1), you'd call it as:
    python Code:
    for x in range(0,2):
        # ...

    Also, when once client is connected to the server, the other cannot connect to the server. Any ideas on how to do this ?
    The server loop continues with processing the data after the accept() call. In order to handle multiple clients, you'll need to spawn a child thread (or process, though that's a bit more involved) to handle that connection, so that the server can continue listening for further connection requests.
    ~~ Peter ~~ :: ( Who am I? ) :: ( Peter's Musings: Uploading myself, bit by bit... ) :: ( Electronic Frontier Foundation ) :: ( I'm a GNU/Linux addict and Free Software Advocate. ) :: ( How to Ask Questions the Smart Way ) :: ( The Fedora Project, sponsored by Red Hat ) :: ( GNOME: The Free Software Desktop Project ) :: ( GnuPG Public Key ) :: ( About me on the WIki )
  12. #7
  13. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,782
    Rep Power
    4300
    You need to modify the server code to be threaded and handle multiple connections. Luckily you can easily implement this in python:
    Code:
    #!/usr/bin/python
    
    import SocketServer
    
    class ThreadedServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
        """
        Practically a do-nothing class which is only there for inheriting the mixin
        for its threading
        """
        pass
    
    class ThreadedHandler(SocketServer.BaseRequestHandler):
        """
        The ThreadedHandler is threaded and instantiates a different connection per
        client. We need to override the handle() method to implement communication 
        to each client.
        """
    
        def handle(self):
            print ("Got client request from", self.client_address[0], self.client_address[1])
            data = self.request.recv(1024)
            print data
            self.request.send('True')
            self.request.close()
    
    HOST = '127.0.0.1'
    PORT = 1999
    # Uncomment the line below and comment the next line for a single threaded server.
    # server = SocketServer.TCPServer((HOST, PORT), ThreadedHandler)
    server = ThreadedServer((HOST, PORT), ThreadedHandler)
    server.serve_forever()
    As you can see, the ThreadedServer class is just multiply-inheriting from SocketServer.ThreadingMixIn and SocketServer.TCPServer and implements no code of its own. As each connection is accepted, it creates a separate thread to handle the client connection.

    If you want to run this as a single threaded server, all you need to do is uncomment one line that I have indicated and comment the next line below. Then, it will go back to the behavior you are seeing in in your original post.

    Comments on this post

    • codergeek42 agrees
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo