开发者

Twisted server for multiple clients

I want to write a server that can accept multiple clients in python (twisted). I am already quite familiar with socket programming with the standard python socket module but here comes the trouble.. I think twisted is really hard to get into and i have read some tutorials about it. But a thing that i can't really find is a simple socket server that accepts multiple connections.. Can anyone help? If i missed some valuable information online please let me know because i am pulling my hair out..

Any help is much appreciated,

Andes开发者_JAVA百科ay


Say, you want to run a server accepting client connections on port 9000:

from twisted.internet import reactor, protocol

PORT = 9000

class MyServer(protocol.Protocol):
    pass

class MyServerFactory(protocol.Factory):
    protocol = MyServer

factory = MyServerFactory()
reactor.listenTCP(PORT, factory)
reactor.run()

And if you want to test connecting to this server, here's the code for a client (to launch in a different terminal):

from twisted.internet import reactor, protocol

HOST = 'localhost'
PORT = 9000

class MyClient(protocol.Protocol):
    def connectionMade(self):
        print "connected!"

class MyClientFactory(protocol.ClientFactory):
    protocol = MyClient

factory = MyClientFactory()
reactor.connectTCP(HOST, PORT, factory)

reactor.run()

You'll notice the code is very similar, only we use a Factory for a server and a ClientFactory for a client, and the servers needs to listen (listenTCP) while the client needs to connect (connectTCP). Good luck!


I think, you did not get the essence of twisted. If you create a twisted socket server it is by default available connection via multiple clients. I would suggested the following tutorials in order and then read the twisted documentation. Write small snippets as its given in these tutorials to understand what is actually happening.

  1. Dave Peticola's twisted tutorial
  2. Itamar Shtull-Trauring's twisted presentation


This tutorial is a great (best) starting point to learn how to write twisted server from scratch: http://twistedmatrix.com/documents/current/core/howto/tutorial/index.html


Twisted is an awesome framework, but this (as often) implies that for easy thing it may be a quite hard...

Here's the fact. You need to write a class that implements a Resource, a LineReceiver if you need, and then attach it to the reactor with:

reactor.connectTCP(<HOST>, <PORT>, istance_of_your_class)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜