Bidirectional Networking

Emanuele D'Arrigo manu3d at gmail.com
Fri Dec 12 12:22:34 EST 2008


Thank you both for the suggestions! Eventually I tried with threading
as illustrated in the code below.
And it works pretty well! The only problem I'm having with it is that
as the server is a daemon the program should end when the client
thread cease to be alive. But it doesn't seem to work that way and I'm
not sure what's going on! I did achieve my objective though. Two
separate instances of the code below will happily send random numbers
to each other for a few seconds!

Manu

-------------------------
To use the following code, cut&paste into two separate *.py files and
invert the port numbers in one file. Then, start them in two separate
shells. WARNING: as mentioned above the two program do not exit and
must be killed, i.e. through the Windows Task Manager or the unix kill
command.
-------------------------

import SocketServer
import socket
import threading
import random
from time import sleep

## Network request handler
class MyTCPHandler(SocketServer.StreamRequestHandler):

    def handle(self):
        self.data = self.rfile.readline().strip()
        print "-> RECV: " + self.data + " - Sent by:" +
self.client_address[0]

## Server Thread
class AsyncServer(threading.Thread):
    def __init__(self, localServer):
        threading.Thread.__init__(self)
        self.server = SocketServer.TCPServer(localServer,
MyTCPHandler)
    def run(self):
        self.server.serve_forever()

## Client Thread
class AsyncClient(threading.Thread):

    def __init__(self, remoteServer):
        threading.Thread.__init__(self)
        self.remoteServer = remoteServer

    def run(self):
        cycle = 0
        while cycle < 1000:

            chance = random.random()
            if(chance < 0.01):

                randomNumber = int(random.random() * 1000)
                message = str(randomNumber) + " from remote cycle " +
str(cycle)

                try:
                    sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
                    sock.connect(self.remoteServer)
                    sock.send(message + "\n")
                    sock.close()
                    print("SENT ->: "+str(randomNumber)+ " by local
cycle "+str(cycle))
                except:
                    print("Failed to send number on cycle "+str
(cycle))
                    pass

            cycle += 1

            sleep(0.01)

## Simulating local/remote servers with different ports
localServer = ("localhost", 9999)
remoteServer = ("localhost", 10000)

asyncServer = AsyncServer(localServer)
asyncServer.daemon = True
asyncServer.start()

asyncClient = AsyncClient(remoteServer)
asyncClient.start()




More information about the Python-list mailing list