!DOCTYPE html html lang = "en" head meta charset = "UTF-8" title Title / title / head body a href = "javascript:WebSocketTest()" Run WebSocker / a div id = "messages" / div / body script var messageContainer = document . getElementById ( "m
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="javascript:WebSocketTest()">Run WebSocker</a>
<div id="messages">
</div>
</body>
<script>
var messageContainer=document.getElementById("messages");
function WebSocketTest() {
if ("WebSocket" in window){
messageContainer.innerHTML='Web Socket is supported by your browser';
var ws=new WebSocket("ws://localhost:8888/websocket?id=1");
ws.onopen=function () {
ws.send("Message To Send");
};
ws.onmessage=function (p1) {
var receivemasg=p1.data;
messageContainer.innerHTML=messageContainer.innerHTML+"<br>Message is received :"+receivemasg;
};
ws.onclose=function (p1) {
messageContainer.innerHTML=messageContainer.innerHTML+"<br>Connection is closed .. :"+receivemasg;
}
}else{
messageContainer.innerHTML="您的电脑不支持webSocker";
}
}
</script>
</html>
import tornado
from tornado.ioloop import IOLoop
import tornado.websocket
import tornado.web
from tornado.options import define,options,parse_command_line
define("port",default=8888,help="run on the given port",type=int)
clients=dict()
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self, *args, **kwargs):
self.render("../templates/index.html")
class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self, *args, **kwargs):
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("Client %s received a message %s "%(self.id,message))
def on_close(self):
if self.id in clients:
del clients[self.id]
print("Client %s is closed "%self.id)
def check_origin(self, origin):
return True
app=tornado.web.Application(handlers=[
(r"/",IndexHandler),
(r"/websocket",MyWebSocketHandler)
],static_path="templates")
import threading
import time
def sendTime():
import datetime
while True:
for key in clients.keys():
msg=str(datetime.datetime.now())
clients[key]["object"].write_message(msg)
print("write to client %s :%s"%(key,msg))
time.sleep(1)
if __name__ == '__main__':
threading.Thread(target=sendTime).start()
parse_command_line()
app.listen(options.port)
IOLoop.instance().start()