OLD | NEW |
| (Empty) |
1 // Copyright 2014 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 define("mojo/public/bindings/js/router", [ | |
6 "mojo/public/bindings/js/codec", | |
7 "mojo/public/bindings/js/connector", | |
8 ], function(codec, connector) { | |
9 | |
10 function Router(handle) { | |
11 this.connector_ = new connector.Connector(handle); | |
12 this.incomingReceiver_ = null; | |
13 this.nextRequestID_ = 0; | |
14 this.responders_ = {}; | |
15 | |
16 this.connector_.setIncomingReceiver({ | |
17 accept: this.handleIncomingMessage_.bind(this), | |
18 }); | |
19 } | |
20 | |
21 Router.prototype.close = function() { | |
22 this.responders_ = {}; // Drop any responders. | |
23 this.connector_.close(); | |
24 }; | |
25 | |
26 Router.prototype.accept = function(message) { | |
27 this.connector_.accept(message); | |
28 }; | |
29 | |
30 Router.prototype.acceptWithResponder = function(message, responder) { | |
31 // Reserve 0 in case we want it to convey special meaning in the future. | |
32 var requestID = this.nextRequestID_++; | |
33 if (requestID == 0) | |
34 requestID = this.nextRequestID_++; | |
35 | |
36 message.setRequestID(requestID); | |
37 this.connector_.accept(message); | |
38 | |
39 this.responders_[requestID] = responder; | |
40 }; | |
41 | |
42 Router.prototype.setIncomingReceiver = function(receiver) { | |
43 this.incomingReceiver_ = receiver; | |
44 }; | |
45 | |
46 Router.prototype.encounteredError = function() { | |
47 return this.connector_.encounteredError(); | |
48 }; | |
49 | |
50 Router.prototype.handleIncomingMessage_ = function(message) { | |
51 var flags = message.getFlags(); | |
52 if (flags & codec.kMessageExpectsResponse) { | |
53 if (this.incomingReceiver_) { | |
54 this.incomingReceiver_.acceptWithResponder(message, this); | |
55 } else { | |
56 // If we receive a request expecting a response when the client is not | |
57 // listening, then we have no choice but to tear down the pipe. | |
58 this.close(); | |
59 } | |
60 } else if (flags & codec.kMessageIsResponse) { | |
61 var reader = new codec.MessageReader(message); | |
62 var requestID = reader.requestID; | |
63 var responder = this.responders_[requestID]; | |
64 delete this.responders_[requestID]; | |
65 responder.accept(message); | |
66 } else { | |
67 if (this.incomingReceiver_) | |
68 this.incomingReceiver_.accept(message); | |
69 } | |
70 }; | |
71 | |
72 var exports = {}; | |
73 exports.Router = Router; | |
74 return exports; | |
75 }); | |
OLD | NEW |