Tornado websocket)

Source: Internet
Author: User

I tested Tornado websocket to implement the functions of the chat room. It is very simple and the code is as follows:

 


Server:


[Python]
Import logging
Import tornado. escape
Import tornado. ioloop
Import tornado. options
Import tornado. web
Import tornado. websocket
Import OS. path
Import uuid
 
From tornado. options import define, options
 
Define ("port", default = 8888, help = "run on the given port", type = int)
 
 
Class Application (tornado. web. Application ):
Def _ init _ (self ):
Handlers = [
(R "/", MainHandler ),
(R "/websocket", ChatSocketHandler ),
]
Settings = dict (
Cookie_secret = "_ TODO: _ GENERATE_YOUR_OWN_RANDOM_VALUE_HERE __",
Template_path = OS. path. join (OS. path. dirname (_ file _), "templates "),
Static_path = OS. path. join (OS. path. dirname (_ file _), "static "),
Xsrf_cookies = True,
)
Tornado. web. Application. _ init _ (self, handlers, ** settings)
 
 
Class MainHandler (tornado. web. RequestHandler ):
Def get (self ):
Self. render ("index.html", messages = ChatSocketHandler. cache)
 
Class ChatSocketHandler (tornado. websocket. WebSocketHandler ):
Waiters = set ()
Cache = []
Cache_size = 200
 
Def allow_draft76 (self ):
# For iOS 5.0 Safari
Return True
 
Def open (self ):
Print "new client opened"
ChatSocketHandler. waiters. add (self)
 
Def on_close (self ):
ChatSocketHandler. waiters. remove (self)
 
@ Classmethod
Def update_cache (cls, chat ):
Cls. cache. append (chat)
If len (cls. cache)> cls. cache_size:
Cls. cache = cls. cache [-cls. cache_size:]
 
@ Classmethod
Def send_updates (cls, chat ):
Logging.info ("sending message to % d waiters", len (cls. waiters ))
For waiter in cls. waiters:
Try:
Waiter. write_message (chat)
Except t:
Logging. error ("Error sending message", exc_info = True)
 
Def on_message (self, message ):
Logging.info ("got message % r", message)
 
ChatSocketHandler. send_updates (message)
 
 
Def main ():
Tornado. options. parse_command_line ()
App = Application ()
App. listen (8080)
Tornado. ioloop. IOLoop. instance (). start ()
 
 
If _ name _ = "_ main __":
Main ()

Import logging
Import tornado. escape
Import tornado. ioloop
Import tornado. options
Import tornado. web
Import tornado. websocket
Import OS. path
Import uuid

From tornado. options import define, options

Define ("port", default = 8888, help = "run on the given port", type = int)


Class Application (tornado. web. Application ):
Def _ init _ (self ):
Handlers = [
(R "/", MainHandler ),
(R "/websocket", ChatSocketHandler ),
]
Settings = dict (
Cookie_secret = "_ TODO: _ GENERATE_YOUR_OWN_RANDOM_VALUE_HERE __",
Template_path = OS. path. join (OS. path. dirname (_ file _), "templates "),
Static_path = OS. path. join (OS. path. dirname (_ file _), "static "),
Xsrf_cookies = True,
)
Tornado. web. Application. _ init _ (self, handlers, ** settings)


Class MainHandler (tornado. web. RequestHandler ):
Def get (self ):
Self. render ("index.html", messages = ChatSocketHandler. cache)

Class ChatSocketHandler (tornado. websocket. WebSocketHandler ):
Waiters = set ()
Cache = []
Cache_size = 200

Def allow_draft76 (self ):
# For iOS 5.0 Safari
Return True

Def open (self ):
Print "new client opened"
ChatSocketHandler. waiters. add (self)

Def on_close (self ):
ChatSocketHandler. waiters. remove (self)

@ Classmethod
Def update_cache (cls, chat ):
Cls. cache. append (chat)
If len (cls. cache)> cls. cache_size:
Cls. cache = cls. cache [-cls. cache_size:]

@ Classmethod
Def send_updates (cls, chat ):
Logging.info ("sending message to % d waiters", len (cls. waiters ))
For waiter in cls. waiters:
Try:
Waiter. write_message (chat)
Except t:
Logging. error ("Error sending message", exc_info = True)

Def on_message (self, message ):
Logging.info ("got message % r", message)

ChatSocketHandler. send_updates (message)


Def main ():
Tornado. options. parse_command_line ()
App = Application ()
App. listen (8080)
Tornado. ioloop. IOLoop. instance (). start ()


If _ name _ = "_ main __":
Main ()
Client:


[Html]
<Html>  
<Body>
 
<Script type = "text/javascript">
 
Var socket;
 
If (! Window. WebSocket ){
 
Window. WebSocket = window. WebSocket;
 
}
 
// Javascript Websocket Client
 
If (window. WebSocket ){
 
Socket = new WebSocket ("ws: // 10.197.60.125: 8080/websocket ");
 
Socket. onmessage = function (event ){
 
Var ta = document. getElementById ('responsetext ');
 
Ta. value = ta. value + '\ n' + event. data
 
};
 
Socket. onopen = function (event ){
 
Var ta = document. getElementById ('responsetext ');
 
Ta. value = "Web Socket opened! ";
 
};
 
Socket. onclose = function (event ){
 
Var ta = document. getElementById ('responsetext ');
 
Ta. value = ta. value + "Web Socket closed ";
 
};
 
} Else {
 
Alert ("Your browser does not support Web Socket .");
 
}
 
// Send Websocket data
 
Function send (message ){
 
If (! Window. WebSocket) {return ;}
 
If (socket. readyState = WebSocket. OPEN ){
 
Socket. send (message );
 
} Else {
 
Alert ("The socket is not open .");
 
}
 
}
 
</Script>
 
<H3> Send:  
<Form onsubmit = "return false;">
 
<Input type = "text" name = "message" value = "Hello World! "/> <Input type =" button "value =" Send Web Socket Data "onclick =" send (this. form. message. value) "/>
 
<H3> Receive:  
<Textarea id = "responseText" style = "width: 500px; height: 300px;"> </textarea>
 
</Form>
 
</Body>
 
</Html>

<Html>

<Body>

<Script type = "text/javascript">

Var socket;

If (! Window. WebSocket ){

Window. WebSocket = window. WebSocket;

}

// Javascript Websocket Client

If (window. WebSocket ){

Socket = new WebSocket ("ws: // 10.197.60.125: 8080/websocket ");

Socket. onmessage = function (event ){

Var ta = document. getElementById ('responsetext ');

Ta. value = ta. value + '\ n' + event. data

};

Socket. onopen = function (event ){

Var ta = document. getElementById ('responsetext ');

Ta. value = "Web Socket opened! ";

};

Socket. onclose = function (event ){

Var ta = document. getElementById ('responsetext ');

Ta. value = ta. value + "Web Socket closed ";

};

} Else {

Alert ("Your browser does not support Web Socket .");

}

// Send Websocket data

Function send (message ){

If (! Window. WebSocket) {return ;}

If (socket. readyState = WebSocket. OPEN ){

Socket. send (message );

} Else {

Alert ("The socket is not open .");

}

}

</Script>

<H3> Send:

<Form onsubmit = "return false;">

<Input type = "text" name = "message" value = "Hello World! "/> <Input type =" button "value =" Send Web Socket Data "onclick =" send (this. form. message. value) "/>

<H3> Receive:

<Textarea id = "responseText" style = "width: 500px; height: 300px;"> </textarea>

</Form>

</Body>

</Html>


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.