websocket(客户端) - xiaogardenz/Work GitHub Wiki
js相关代码
//初始化socket
var s = new ws({host: window.socketIp, port: window.socketPort, openedCallback: function () {
//回调
}
});
window.ws = window.ws || function(option){
self = this;
self.msg = function(type, data){
return JSON.stringify({
uuid: Date.now(),
type: type,
data: data
});
};
self.auth = function(userId, userType, token){
self.res.send(self.msg('verify', {
userId: userId,
userType: userType,
token: token
}));
};
self.send = function(type, data) {
self.res.send(self.msg(type, data));
}
if (!window._ws || window._ws.readyState != window._ws.OPEN) {
window._ws = new WebSocket('ws://'+ option.host + ':' + option.port);
}
self.res = window._ws;
self.res.onopen = function(){
console.info('WebSocket Connection is Success');
typeof option.openedCallback == 'function' && option.openedCallback();
};
self.res.onmessage = function(event){
try {
//成功,相关代码回调
} catch (error) {
console.error(error);
}
};
self.res.onclose = function(event) {
socketClose();
console.warn('WebSocket Connection [CLOSE]');
};
}