HTML and CSS Reference
In-Depth Information
Creating a Simple Echo Server
You can demonstrate that ease of use by creating a simple echo server. Once it is running, the server will send
back whatever data you send it. For the server side of things, you will be using Python. It was chosen because the
server-side code is concise and easy to understand. To begin, you will need to have Python ( http://python.org ) installed
on your machine. You will be using the Python web framework Tornado because of its great WebSocket support.
If you don't already have Tornado installed, you can do so with the following command, run from any directory:
sudo easy_install tornado
Start the server by executing python tornado-demo.py in the same directory as the file; navigate to
http://localhost:8888 to see it in action. You do not have to understand fully the Python in Listing 11-4 to see
that it closely mirrors the JavaScript WebSocket API. You do some setup when the socket is opened, send a message
immediately back to the client when you receive it, and close the connection when the client requests it.
Listing 11-4. Python Example: Open Socket, Send Message, Close Connection
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self, *args):
self.id = self.get_argument("Id")
self.stream.set_nodelay(True)
clients[self.id] = {"id": self.id, "object": self}
def on_message(self, message):
# Print to console when message received
# Write same message to client
print "Client %s sent a message : %s" % (self.id, message)
self.write_message(message)
def on_close(self):
if self.id in clients:
del clients[self.id]
On the client, you begin by instantiating a WebSocket connection. The universally unique identifier (UUID)
allows each client to have his or her own ID and to receive only the messages targeted to the client. Other libraries,
which you will investigate later in the chapter, do this bookkeeping for you. After the WebSocket object is created, you
define the handlers that respond to events, as shown in Listing 11-5 and Figure 11-2 .
Listing 11-5. Create the WebSocket Object, Define Event Handlers
var ws = new WebSocket("ws://localhost:8888/ws?Id="+Math.uuid());
ws.onopen = function() {
messageContainer.innerHTML += "Preparing to send message";
ws.send("The time is now "+ new Date());
messageContainer.innerHTML += "Sent message."
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
messageContainer.innerHTML += "Message received: "+received_msg;
};
 
Search WWH ::




Custom Search