js
function init() {
var ws = new WebSocket("ws://localhost:8080");
//申请一个WebSocket对象,参数是服务端地址,同http协议使用http://开头一样,WebSocket协议的url使用ws://开头,另外安全的WebSocket协议使用wss://开头
ws.onopen = function () {
//当WebSocket创建成功时,触发onopen事件
console.log("open");
ws.send("hello"); //将消息发送到服务端
}
ws.onmessage = function (e) {
//当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
console.log(e.data);
}
ws.onclose = function (e) {
//当客户端收到服务端发送的关闭连接请求时,触发onclose事件
console.log("close");
}
ws.onerror = function (e) {
//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
console.log(e);
}
}
window.addEventListener("load", init, false);
wsServer.py
from SimpleWebSocketServer.SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
import threading
from websocket import WebSocket
from main import logger
'''
used by wsClient to obtain the elevState update and dispatch update
'''
from SimpleWebSocketServer.SimpleWebSocketServer import WebSocket
clients = []
class ElevWSHandler(WebSocket):
''' BUG: don't add __init__ method here, WebSocket Handle cannot be init correctly? '''
''' not same with DispatchServer.TCPHandler, __call__ cannot be invoked '''
# @FIXME: use __init__ and __call__ does not work, so logger cannot be passed into it
# static variable
@staticmethod
def init(logger):
ElevWSHandler._logger = logger
'''
def __init__(self, dispatchCenter, logger):
self.logger = logger
self.dispatchCenter = dispatchCenter
# Websocket(self, sock, address) will trigger method __call__
def __call__(self, server, sock, address):
WebSocket.__init__(self, server, sock, address)
return self
'''
def handleMessage(self):
# self.logger.info(self.data)
ElevWSHandler._logger.info(self.data)
def handleConnected(self):
# self.logger.info("{} WS: 1 wsClient connected".format(self.address))
clients.append(self)
ElevWSHandler._logger.warn("------------------------------------------------------------")
ElevWSHandler._logger.warn("{} WS: 1 wsClient connected, total:{}".format(self.address, len(clients)))
''' BUG FIX: connection is closed by server side, why? '''
# ElevWSHandler._dispatchCenter.sendAllInitMsg()
# send existing user & group info to clients
# {”c”:”INIT”, groups: [
# { “g”:0, “users”:[{“n”:”fisher”, f:”3”},{…}]},
# { “g”:1, “users”:[{“n”:”W”, f:”2”},{…}]}
# ] }
def handleClose(self):
# self.logger.info("{} channel closed".format(self.address))
ElevWSHandler._logger.warn("---------------------------------------")
ElevWSHandler._logger.warn("{} channel closed".format(self.address))
clients.remove(self)
class ElevWSServer(threading.Thread):
def __init__(self, port, logger):
threading.Thread.__init__(self, name="ElevWSServer")
self.port = port
self.logger = logger
def run(self):
# server = SimpleWebSocketServer('', self.port, ElevWSHandler(self.dispatchCenter, self.logger), selectInterval = 1)
server = SimpleWebSocketServer('', self.port, ElevWSHandler, selectInterval=1)
self.logger.warn("------------------------------------------------------")
self.logger.warn("WebSocket Server listening on :{}".format(self.port))
self.logger.warn("------------------------------------------------------")
server.serveforever()
if __name__ == '__main__':
ElevWSHandler.init(logger)
elevWSServer = ElevWSServer(8080, logger).start()