我有以下代码片段,我需要扩展它来定义多个WebSockets,我对如何解决这个问题一无所知:
var registerWebSocketHandlers = function(webSocket) {
webSocket.onclose = function(){
setTimeout(service.reopen, reconnectTimeout *= 2);
};
webSocket.onopen = function(e) {
icc.publish('webSocket.reconnect');
reconnectTimeout = defaultReconnectTimeout; //reset this
deferredSend();
};
webSocket.onerror = function(e) {
throw new Error("[WebSocket] An error occured " + e);
};
}
var openConnection = function() {
connectionWasOpenBefore = true;
webSocket = new $window.WebSocket(xyz);
webSocket.id = uniqid();
registerWebSocketHandlers(webSocket);
};
var uniqid = function() {
return (new Date().getTime()).toString(16);
}
service.setMessageEventHandler = function(cb) {
webSocket.onmessage = function(msg) {
if(msg.data.indexOf('Status: connected') === 0)
{
return;
}
var jsonObj = JSON.parse(msg.data);
cb(jsonObj);
};
};
如何扭曲代码以满足多个WebSockets的需要并为其附加适当的回调?
答案 0 :(得分:0)
使用多重模式。
var firstWebSocket = SocketFactory.getInstance('firstSocket');
// It would probably be a good idea to add this listener in the SocketFactory instead and broadcast an event when there's a message so multiple listeners can respond to it.
firstWebSocket.onmessage = function(){...};
var secondWebSocket = SocketFactory.getInstance('secondSocket');
secondWebSocket.onmessage = function(){...};
这将按名称分隔您的不同websockets。使用getInstance('无论如何')来获得标记为'的任何'。
if (isset($_GET['search'])) {
if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
header('Location: http://'.$_SERVER['HTTP_HOST'].'/offstreams/search/'.urlencode($_GET['search']));
exit();
}
echo $_GET['search'];
}
接下来,您可以从任何其他区域按实例名称访问配置的websockets。
?