Working with Sockets in Python

Alright this one is super hacky so bare with me.  This code is almost a direct port from Python’s offical docs.  I just added a few coroutine functions just for the fun of it.  Anyway if you want to learn more about sockets, read the docs and Doug Hellmann also covers socket programming in Python.

 

Later I’ll try doing a quick write up for this one. In case you’re reading this and able to decode it, you might want to check out David Beazley’s buses to dict example. Broadcasting seemed pretty cool too me and I going to try something similar in the realm of socket programming.

As of now, this one is still buggy and doesn’t fully work yet. Currently the problems seem to be at listening on multiply ports. I’m not entire sure how to do this in my own “branchy” way yet, if you’re curious on python libraries that might solve this take a look at Twisted or the built in library of SocketServer but don’t quote me on this, I haven’t tried using Twisted before and SocketServer doesn’t really interests me.

# Echo client program
import socket

def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.__next__()
        return(cr)
    return(start)

def pushMessage( message, target ):
    target.send(message)
    
@coroutine
def toServer( ip, port, target ):
    while True:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
        message = (yield)
        
        if(message != None):
            sock.connect( (ip, port) )
            print('Sending message to the server')
            sock.send( message )
            target.send( sock.recv(1024) )
            print('Closing socket')
            sock.close()

@coroutine
def printer():
    while True:
        print( 'Incoming message from the server: ', (yield) )

@coroutine
def broadcast(targets):
    while True:
        item = (yield)
        for target in targets:
            target.send(item)
  
if __name__ == '__main__':
    pushMessage( b'Hello World!',
              broadcast([
                toServer( '127.0.0.1' , 50007, printer() ),
                toServer( '127.0.0.1' , 50008, printer() )
                  ]) )
# Echo server program
import socket

def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.__next__()
        return(cr)
    return(start)

def portListener( ports, target ):
    for port in ports:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind( ('', port) )
        sock.listen(5)
        print('Listing on port: ', port)
        target.send( sock.accept() )
    
@coroutine
def socketConnection( ):
    conn, addr = (yield)        
    
    try:
        message = conn.recv(1024)
        print('Incoming message ', message)
        conn.send( message )

    except:
        pass        

if __name__ == '__main__':
   portListener( (50007,50008), socketConnection() )
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s