4

I am in the process of designing some hardware interface with python. what I need to do is as follows,

~initialize the drivers ~start the device ~create a socket at port 2626 and wait for clients to connect for receiving data ~if any client got connected then send the hello message while serving all other connected client and add this client to the connected client list. ~if any event happened on the device lets say temperature raise is detected then through this event data to all connected clients. ~any connected clients can ask the server for any specific data.

This is my process. I got the device part working great now its printing data to console and for the socket server I have this following code this working fine as I expect. but what is problem is after calling "run()" its going inside the while loop. its obvious though. when I am listening for new connections I am not able to call any other function.

while listening for connections I should be able to send / recv. any ideas how to do this?

this is my server program which is working fine for listening for connections. while listening you are not allowed to to anything. :(

#!/usr/bin/env python

import socket
import select

class ChatServer:

    def __init__( self, port ):
        self.port = port;

        self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
        self.srvsock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
        self.srvsock.bind( ("", port) )
        self.srvsock.listen( 5 )

        self.descriptors = [self.srvsock]
        print 'Server started on port %s' % port

    def run( self ):
        while 1:
            # Await an event on a readable socket descriptor
            (sread, swrite, sexc) = select.select( self.descriptors, [], [] )
            # Iterate through the tagged read descriptors
            for sock in sread:
                # Received a connect to the server (listening) socket
                if sock == self.srvsock:
                    self.accept_new_connection()
                else:
                    # Received something on a client socket
                    str = sock.recv(100)

                    # Check to see if the peer socket closed
                    if str == '':
                        host,port = sock.getpeername()
                        str = 'Client left %s:%s\r\n' % (host, port)
                        self.broadcast_string( str, sock )
                        sock.close
                        self.descriptors.remove(sock)
                    else:
                        host,port = sock.getpeername()
                        newstr = '[%s:%s] %s' % (host, port, str)
                        self.broadcast_string( newstr, sock )

    def accept_new_connection( self ):
        newsock, (remhost, remport) = self.srvsock.accept()
        self.descriptors.append( newsock )

        newsock.send("You're connected to the Python server\r\n")
        str = 'Client joined %s:%s\r\n' % (remhost, remport)
        self.broadcast_string( str, newsock )

    def broadcast_string( self, str, omit_sock ):
        for sock in self.descriptors:
            if sock != self.srvsock and sock != omit_sock:
                sock.send(str)
        print str,

myServer = ChatServer( 2626 ).run()

Thanks in advance for all your help :)

2
  • 1
    Use Twisted? Commented Feb 16, 2012 at 6:29
  • @MikeCooper thanks for your suggestion buddy. I am new to python. do you have any samples or could you point to some tutorials for quick start? Commented Feb 16, 2012 at 6:59

3 Answers 3

1

Since twisted is out of question, I suggest using the socketserver module.

For an easy start, see this example.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for all your suggestion. I got this working with socketServer. :)
1

You need to make all sockets non-blocking.

5 Comments

@San If you make the sockets (server socket too) non-blocking, then I see no problem with the code you provided.
I have tried that too. for your ref I am connecting to this from a nodejs script. nodejs is working fine on that way. I need to get rid of the while loop. its halting my program.
After instantiating the class and calling run() method if i say print "you can do whatever while I am listening" this never gets executed.
@San Ah, I think I know what you mean! One solution is to add a timeout to the select call, and if it times out you can do something else and then go back to poll the sockets. Another solution is to put the whole networking loop in a separate thread.
yes buddy, you got my point. I am new to python just started a week before. I have no Idea of executing the socketserver in a separate thread. and one more point it on the fly if i got any hardware event I need to push the event data to the socket. any idea on this. Thanks a lot for helping on this buddy.
1

Use Twisted

An example that shows asynchronous networking with core python is here.

6 Comments

...or socketserver (SocketServer for python 2.x)
@Kimvais are you talking about without using twisted? I have started with python last week only. if you can point some samples I will be more thankful to you.
@San - if you don't have any external limitations that you can not use twisted - use it. The tutorial is a good start.
@Kimvais - actually I do have such limitations. if it is not possible using pure python, then I have to go for it. twisted looks bulky. these programs I am writing is going to run on less memory devices and not on huge servers. so I prefer doing with pure python.
@san - You can do asynchronous network programming with core python but it'll take you more work and time, and if you're a beginner in python then you'll have a steep learning curve.
|

Your Answer

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.