Multi client chat server in Twisted Python

In a multi client chat server, N clients are connected to a server and send messages. In this program, one of the clients send messages to the server and it will send back the messages to all other clients. I implemented it in Twisted Python also.

Twisted is an event-driven networking engine written in Python and licensed under the open source. Twisted makes it easy to implement custom network applications, both servers and clients.It gives developers a complete set of tools for communicating across networks and the Internet. Twisted includes both high- and low-level tools.

This program also uses TCP.

Client:

The twisted event loop is started by starting the reactor. Starting the reactor is easy. Import the reactor object from the twisted.internet module. Then call reactor.run( ) to start the reactor’s event loop. Call the reactor.connectTCP( ) method to start a TCP connection, passing a StdioProxyFactory object as the third parameter. The StdioProxyFactory object waits for the connection to be established, and then creates a Protocol object that manages the flow of data back and forth along that connection. Use a subclass of Protocol to send and receive data. Override the dataReceived method to control what happens when data is received from the connection. Use self.transport.write to send data.

Keyboard input is given by importing stdio from twisted.internet.

This program includes a class called DataForwardingProtocol, which takes any data received and writes it to self.output. This usage makes it possible to create a simple application, similar to the classic utility netcat, that passes any data received on standard input to a server, while printing any data received from the server to standard output.

Server:

Twisted server accepts connections from clients and interacts with them by creating a Protocol object defining our server’s behavior. Create a MultiClientEchoFactory object using the Protocol, and pass it to reactor.listenTCP. The list self.clients defined in the factory stores clients connections. Whenever a data is received from one of the clients, the server send back this data to all clients in the clients list.

The complete code of this program is available in https://bitbucket.org/vidyakv/twisted-python/changeset/7db7480a1dc8

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The WordPress.com Blog

The latest news on WordPress.com and the WordPress community.

%d bloggers like this: