Re: A lot of questions... again

Right, understand that this is still a basic example, there's quite a bit more that could be added to it, like recionnection attempts, timeouts, etc. In this setup the script acts as both client and server, so you need to press "s" to start the server, then "c" to connect to it locally. You can then press space where it will send a packet across, you'll also notice that it prints things twice, this is not a bug. When you connect it will add two user echo() classes to the user list, one is for the client side, the other for the server side. In practice there would be only one of these in the list depending on whether your strictly the server or the client, but thats not really relevant at the moment. You can press "q" to quit or "d" to disconnect clients from the server side.

import pyglet
from pyglet.window import key
from pyglet import clock

from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet.protocol import ClientFactory
from twisted.internet import reactor
from twisted.internet import task

import pickle
import zlib
import random

pyglet.options['debug_gl'] = False

#primary window/game class
class Prototype(pyglet.window.Window):
    def __init__(self):
        super(Prototype, self).__init__(640, 480, resizable=False, fullscreen=False, caption="Test")
        self.clear()

    #server side connected user variable, when someone connects the Echo Class will add itself into it.
    #then just call self.user.sendData to transmit to the connected user or check self.user.inbox to get data.
        self.user = []

        self.server = None
        self.client = None

    #since the Reactor is in control, to properly run the main game loop you have to manually call the clock.
    #this variable is to keep track of the last time the clock was ticked.
        self.old_dt = clock.tick()
        self.fps_display = pyglet.clock.ClockDisplay()


#shutdown program gracefully
    def shutdown(self, result):
        reactor.stop()

#system error shutdown
    def bailout(self, reason):
        reason.printTraceback()
        reactor.stop()

#main game loop
    def update(self):
        while not self.has_exit:
        #manually dispatch window events (since twisted reactor is in control)
            self.dispatch_events()

        #Make sure events are timed properly while coiterating with network layer. That and tick clock events like the fps counter and game pacing.
            dt = clock.tick()
            self.old_dt = self.old_dt + dt

        #if enough time has passed, update game state
            if self.old_dt >= 0.025:
                self.old_dt = 0

                self.clear()

                for a in self.user:
                    print(a.inbox)
                    a.inbox = []

                self.fps_display.draw()


        #draw here and manually flip frame buffers
            self.flip()

        #return control to twisted Reactor
            yield 1

                    
    def on_key_release(self,symbol, modifiers):
    #start server
        if symbol == key.S:
            self.server = TCP4ServerEndpoint(reactor, 8007)
            self.server.listen(QOTDFactory())
            print("server initializing")
    #connect to server
        if symbol == key.C:
            self.client = reactor.connectTCP('localhost', 8007, EchoClientFactory())
            print("connecting")
    #disconnect client from server side
        if symbol == key.D:
            for a in range(0,len(self.user),1):
                self.user[a].disconnect()

        if symbol == key.Q:
            if self.client != None:
            #disconnect from the client side
                print('stopping client')
                self.client.disconnect()
            self.close()

        if symbol == key.SPACE:
            for a in self.user:
                a.sendData("space pressed")



#this handles two way communication with connected clients
class Echo(Protocol):
#data reciever class
    def connectionMade(self):
    #add this class to the main program
        window.user.append(self)
    #stored incoming data
        self.inbox = []

    def dataReceived(self, data):
        data = ""
        data = ""
        self.inbox.insert(0,data)

    def sendData(self,data):
        data = ""
        data = ""
        self.transport.write(data)

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



#this monitors the port and automatically calls Echo() when someone connects, passing their address to it.
class QOTDFactory(Factory):
    def buildProtocol(self, addr):
        print(addr, "connected.")
        return Echo()



#This class establishes a connection to a server.
class EchoClientFactory(ClientFactory):
    def startedConnecting(self, connector):
        print('Started to connect.')

    def buildProtocol(self, addr):
        print('Connected.')
        return Echo()

    def clientConnectionLost(self, connector, reason):
        print('Lost connection. Reason:', reason)

    def clientConnectionFailed(self, connector, reason):
        print('Connection failed. Reason:', reason)



if __name__ == '__main__':
#initialize main window
    window = Prototype()
#port to listen to
    task.coiterate(window.update()).addCallback(window.shutdown).addErrback(window.bailout)
#start reactor loop
    reactor.run()
-- 
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector
  • ... AudioGames . net Forum — Developers room : amerikranian via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : ivan_soto via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : magurp244 via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : magurp244 via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : dardar via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : Ethin via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : amerikranian via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : amerikranian via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : magurp244 via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : amerikranian via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : magurp244 via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : magurp244 via Audiogames-reflector
  • ... AudioGames . net Forum — Developers room : ashleygrobler04 via Audiogames-reflector

Reply via email to