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,
Andesay
In the basic model, server handles only one client at a time, which is a big assumption if you want to develop any scalable server model. The simple way to handle multiple clients would be to spawn new thread for every new client connected to the server.
A multiple client server is a type of software architecture for computer networks where clients request information from a server computer. The most common type of multiple client server system for small businesses and homes is the single server with multiple clients.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With