tcp_server.py

"""Start a TCP server.
   On mouse click send a message to all clients.
   by stephan)
"""
from slut import *
from slut.net import TcpServer
from twisted.internet.protocol import Protocol
#HINT: you can use any other protocol from twisted
#see http://twistedmatrix.com/


class Atlantis(World):
    def onSetup(self):
        self.name = "RJ45 Plugs Are Awesome"
        self.tcpserver = TcpServer(4114, StandardServer)
        self.clients = []

    def onDrawOrtho(self):
        circle(200, 200, len(self.clients)*5)

    def onMouseButtonDown(self, event):
        #broadcast to all clients
        for client in self.clients:
            client.write('Nice to be connected with you.')



class StandardServer(Protocol):
    def connectionMade(self):
        print 'connection established'
        glo.world.clients.append(self)

    def lineReceived(self, line):
        print 'line received: ', line

    def connectionLost(self, reason):
        print 'connection lost: ', reason

    def write(self, line):
        if self.connected:
            self.transport.write(line)
        else:
            print 'not connected'

    def disconnect(self):
        self.transport.loseConnection()


atlantis = Atlantis()
atlantis.run()
Initiated by Stephan Hechenberger
Thanks to CADRE's 103