Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Convert samples to use chrome.sockets APIs available in Chrome 33 #205

Closed
wants to merge 14 commits into from

6 participants

@rpaquay
Collaborator

No description provided.

@mangini mangini commented on the diff
parrot-ar-drone/lib/API.js
@@ -179,13 +180,38 @@ DRONE.API = (function() {
if (SIMULATE) {
callbacks.onConnected(1);
} else {
- chrome.socket.create(sockRef.protocol, undefined, function(sockInfo) {
- sockRef.socket = sockInfo.socketId;
- chrome.socket[sockRef.type](sockRef.socket,
- sockRef.direction===TO_DRONE?DRONE_IP:CLIENT_IP,
- sockRef.port,
- callbacks.onConnected);
+ //chrome.socket.create(sockRef.protocol, undefined, function (sockInfo) {
+ // sockRef.socket = sockInfo.socketId;
@mangini Owner
mangini added a note

Any reason to keep this code commented instead of removing it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@mangini mangini commented on the diff
parrot-ar-drone/manifest.json
((11 lines not shown))
-
- "udp-bind::5556",
- "udp-send-to::5556",
-
- "udp-bind::5559",
- "udp-send-to::5559"]
- }]
+ "permissions": ["system.network"],
+ "sockets": {
+ "udp": {
+ "bind": ":5554",
+ "send": ":5554",
+ "bind": ":5556",
+ "send": ":5556",
+ "bind": ":5559",
+ "send": ":5559",
@mangini Owner
mangini added a note

Is this a valid syntax? Repeated keys in JSON dicts usually means the previous values are replaced, which would make this equivalent to "udp": {"bind": ":5559", "send": ":5559"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@mangini mangini commented on the diff
udp/manifest.json
@@ -3,16 +3,16 @@
"name": "Sample of UDP Network Access",
"description": "Echo..... Echo.",
"version": "2",
@mangini Owner
mangini added a note

Please, bump the version of all modified samples, so they can be updated in CWS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@djdeath

How is this supposed to work?
Where are the 't' and 'acceptInfo' variable coming from?

@scheib
Collaborator

@rpaquay, update/respond to issues? Is this patch moving forward?

@rpaquay rpaquay was assigned by kalman
@antonysargent
Collaborator

FYI, @rpaquay is looking at this again, and has opened https://code.google.com/p/chromium/issues/detail?id=392669 for tracking.

@SEIAROTg

I've already made a HTTP server with chrome.sockets at https://github.com/SEIAROTg/chrome.httpServer

@rpaquay rpaquay Merge remote-tracking branch 'upstream/master' into chrome.sockets.m33
Conflicts:
	mdns-browser/main.js
	mdns-browser/manifest.json
7080750
@rpaquay
Collaborator

Closing this pull request, will be creating new ones later (one per sample).

@rpaquay rpaquay closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Dec 16, 2013
  1. @rpaquay
Commits on Dec 17, 2013
  1. @rpaquay

    Fix API conversion leftover.

    rpaquay authored
  2. @rpaquay
Commits on Dec 19, 2013
  1. @rpaquay
  2. @rpaquay

    Cleanup telnap app sample.

    rpaquay authored
  3. @rpaquay

    Typo.

    rpaquay authored
Commits on Dec 20, 2013
  1. @rpaquay
  2. @rpaquay
  3. @rpaquay
Commits on Jan 10, 2014
  1. @rpaquay
  2. @rpaquay
Commits on Feb 19, 2014
  1. @rpaquay
Commits on Feb 25, 2014
  1. @rpaquay

    Convert CRLF to LF.

    rpaquay authored
Commits on Aug 7, 2014
  1. @rpaquay

    Merge remote-tracking branch 'upstream/master' into chrome.sockets.m33

    rpaquay authored
    Conflicts:
    	mdns-browser/main.js
    	mdns-browser/manifest.json
This page is out of date. Refresh to see the latest.
View
18 image-edit/background.js
@@ -1,9 +1,9 @@
-chrome.app.runtime.onLaunched.addListener(
- function(launchData) {
- chrome.app.window.create(
- 'index.html',
- { id: "window" },
- function(win) {
- win.contentWindow.launchData = launchData;
- });
- });
+chrome.app.runtime.onLaunched.addListener(
+ function(launchData) {
+ chrome.app.window.create(
+ 'index.html',
+ { id: "window" },
+ function(win) {
+ win.contentWindow.launchData = launchData;
+ });
+ });
View
7 mdns-browser/main.js
@@ -125,6 +125,11 @@ ServiceFinder.prototype.ips = function(opt_service) {
* @private
*/
ServiceFinder.prototype.onReceive_ = function(info) {
+/**
+ * Handles an incoming UDP packet.
+ * @private
+ */
+ServiceFinder.prototype.onReceive_ = function (info) {
var getDefault_ = function(o, k, def) {
(k in o) || false == (o[k] = def);
return o[k];
@@ -173,7 +178,7 @@ ServiceFinder.prototype.broadcast_ = function(sock, address) {
chrome.sockets.udp.send(sock, raw, '224.0.0.251', 5353, function(sendInfo) {
if (sendInfo.resultCode < 0)
this.callback_('Could not send data to:' + address);
- });
+ }.bind(this));
};
ServiceFinder.prototype.shutdown = function() {
View
1  mdns-browser/manifest.json
@@ -3,6 +3,7 @@
"description": "Browses mDNS services on the local network",
"manifest_version": 2,
"version": "0.7",
+ "minimum_chrome_version": "33.0.1715.0",
"app": {
"background": {
"scripts": ["background.js"]
View
57 multicast/MulticastSocket.js
@@ -7,6 +7,8 @@
*/
function MulticastSocket(config) {
this.config = config;
+ this._onReceive = this._onReceive.bind(this);
+ this._onReceiveError = this._onReceiveError.bind(this);
}
function emptyFn() {
@@ -24,24 +26,25 @@ mc_proto.onDisconnected = function () {
mc_proto.connect = function (callback) {
var me = this;
- chrome.socket.create('udp', function (socket) {
+ chrome.sockets.udp.create(function (socket) {
var socketId = socket.socketId;
- chrome.socket.setMulticastTimeToLive(socketId, 12, function (result) {
+ chrome.sockets.udp.setMulticastTimeToLive(socketId, 12, function (result) {
if (result != 0) {
me.handleError("Set TTL Error: ", "Unkown error");
}
- chrome.socket.bind(socketId, "0.0.0.0", me.config.port, function (result) {
+ chrome.sockets.udp.bind(socketId, "0.0.0.0", me.config.port, function (result) {
if (result != 0) {
- chrome.socket.destroy(socketId);
+ chrome.sockets.udp.close(socketId);
me.handleError("Error on bind(): ", result);
} else {
- chrome.socket.joinGroup(socketId, me.config.address, function (result) {
+ chrome.sockets.udp.onReceive.addListener(me._onReceive);
+ chrome.sockets.udp.onReceiveError.addListener(me._onReceiveError);
+ chrome.sockets.udp.joinGroup(socketId, me.config.address, function (result) {
if (result != 0) {
- chrome.socket.destroy(socketId);
+ chrome.sockets.udp.close(socketId);
me.handleError("Error on joinGroup(): ", result);
} else {
me.socketId = socketId;
- me._poll();
me.onConnected();
if (callback) {
callback.call(me);
@@ -57,34 +60,34 @@ mc_proto.connect = function (callback) {
mc_proto.disconnect = function (callback) {
var socketId = this.socketId;
this.socketId = undefined;
- chrome.socket.destroy(socketId);
+ chrome.sockets.udp.onReceive.removeListener(me._onReceive);
+ chrome.sockets.udp.onReceiveError.removeListener(me._onReceiveError);
+ chrome.sockets.udp.close(socketId);
this.onDisconnected();
if (callback) {
callback.call(this);
}
};
+mc_proto._onReceive = function (info) {
+ if (info.socketId != this.socketId)
+ return;
+ this.onDiagram(info.data, info.remoteAddress, info.remotePort);
+};
+
+mc_proto._onReceiveError = function (info) {
+ if (info.socketId != this.socketId)
+ return;
+ this.handleError("", info.resultCode);
+ this.disconnect();
+};
+
mc_proto.handleError = function (additionalMessage, alternativeMessage) {
var err = chrome.runtime.lastError;
err = err && err.message || alternativeMessage;
this.onError(additionalMessage + err);
};
-mc_proto._poll = function () {
- var me = this;
- if (me.socketId) {
- chrome.socket.recvFrom(me.socketId, 1048576, function (result) {
- if (result.resultCode >= 0) {
- me.onDiagram(result.data, result.address, result.port);
- me._poll();
- } else {
- me.handleError("", result.resultCode);
- me.disconnect();
- }
- });
- }
-};
-
mc_proto.arrayBufferToString = function (arrayBuffer) {
// UTF-16LE
return String.fromCharCode.apply(String, new Uint16Array(arrayBuffer));
@@ -107,21 +110,21 @@ mc_proto.sendDiagram = function (message, callback, errCallback) {
if (message && message.byteLength >= 0 && this.socketId) {
var me = this;
try {
- chrome.socket.sendTo(this.socketId,
+ chrome.sockets.udp.send(this.socketId,
message,
this.config.address,
this.config.port,
function (result) {
- if (result.bytesWritten >= 0) {
+ if (result.resultCode >= 0) {
if (callback) {
callback.call(me);
}
} else {
if (errCallback) {
- errCallback()
+ errCallback();
} else {
me.handleError("");
- if (result.bytesWritten == -15) {
+ if (result.resultCode == -15) {
me.disconnect();
}
}
View
15 multicast/manifest.json
@@ -2,7 +2,7 @@
"name": "Multicast Chat Sample",
"version": "0.2",
"manifest_version": 2,
- "minimum_chrome_version": "27",
+ "minimum_chrome_version": "33.0.1715.0",
"description": "Sending/Receiving multicast diagrams.",
"app": {
"background": {
@@ -17,10 +17,13 @@
"128": "128.png"
},
- "permissions": [
- "storage",
- {
- "socket": ["udp-send-to", "udp-bind", "udp-multicast-membership"]
+ "permissions": ["storage"],
+
+ "sockets": {
+ "udp": {
+ "send": "",
+ "bind": "",
+ "multicastMembership": ""
}
- ]
+ }
}
View
11 parrot-ar-drone/README.md
@@ -3,8 +3,10 @@
# Parrot AR.Drone 2.0 Controller
-This app uses the [Gamepad API](http://www.html5rocks.com/en/tutorials/doodles/gamepad/) and the [chrome.socket API](http://developer.chrome.com/apps/socket.html) to communicate with
-a [Parrot AR.Drone 2.0](http://ardrone2.parrot.com/).
+This app uses the [Gamepad API](http://www.html5rocks.com/en/tutorials/doodles/gamepad/),
+the [chrome.sockets.udp API](http://developer.chrome.com/apps/sockets.udp.html) and
+the [chrome.sockets.tcp API](http://developer.chrome.com/apps/sockets.tcp.html) to
+communicate with a [Parrot AR.Drone 2.0](http://ardrone2.parrot.com/).
The SDK specifies that there are 4 socket connections:
@@ -32,10 +34,11 @@ _Please note: this has only been tested with an Xbox 360 controller_
* [Runtime](http://developer.chrome.com/apps/app.runtime.html)
* [Window](http://developer.chrome.com/apps/app.window.html)
-* [Socket](http://developer.chrome.com/apps/socket.html)
+* [UDP Socket](http://developer.chrome.com/apps/socket.udp.html)
+* [TCP Socket](http://developer.chrome.com/apps/socket.tcp.html)
_Thanks to felixge for the [Node AR Drone lib](https://github.com/felixge/node-ar-drone), which served as a helpful reference._
-
+
## Screenshot
![screenshot](https://raw.github.com/GoogleChrome/chrome-app-samples/master/parrot-ar-drone/assets/screenshot_1280_800.png)
View
104 parrot-ar-drone/lib/API.js
@@ -83,6 +83,7 @@ DRONE.API = (function() {
if(connectionsOutstanding === 0 && callbacks.onAllConnected) {
// start sending commands
+ startReceivingData();
sendKeepAliveCommand();
sendFlatTrim();
sendSensitivity();
@@ -118,7 +119,7 @@ DRONE.API = (function() {
function bootstrapClientIp() {
// double check the Client IP (sometimes the Drone assignes 192.168.1.3)
- chrome.socket.getNetworkList(function(entries) {
+ chrome.system.network.getInterfaceList(function(entries) {
if (entries) for (var i=0; i<entries.length; i++) {
if (entries[i] && entries[i].address
&& entries[i].address.indexOf("192.168.1.")==0) {
@@ -160,9 +161,9 @@ DRONE.API = (function() {
* Closes and discards all the socket connections
*/
function shutdown() {
- disconnect(sockets['at'].socket);
- disconnect(sockets['nav'].socket);
- disconnect(sockets['cmd'].socket);
+ disconnect(sockets['at']);
+ disconnect(sockets['nav']);
+ disconnect(sockets['cmd']);
// TODO: disconnect(sockets['vid'].socket);
}
@@ -179,13 +180,38 @@ DRONE.API = (function() {
if (SIMULATE) {
callbacks.onConnected(1);
} else {
- chrome.socket.create(sockRef.protocol, undefined, function(sockInfo) {
- sockRef.socket = sockInfo.socketId;
- chrome.socket[sockRef.type](sockRef.socket,
- sockRef.direction===TO_DRONE?DRONE_IP:CLIENT_IP,
- sockRef.port,
- callbacks.onConnected);
+ //chrome.socket.create(sockRef.protocol, undefined, function (sockInfo) {
+ // sockRef.socket = sockInfo.socketId;
@mangini Owner
mangini added a note

Any reason to keep this code commented instead of removing it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ // chrome.socket[sockRef.type](sockRef.socket,
+ // sockRef.direction === TO_DRONE ? DRONE_IP : CLIENT_IP,
+ // sockRef.port,
+ // callbacks.onConnected);
+ //});
+ if (sockRef.protocol == "udp") {
+ chrome.sockets.udp.create({}, function (sockInfo) {
+ sockRef.socket = sockInfo.socketId;
+ if (sockRef.type == "bind") {
+ chrome.sockets.udp.bind(sockRef.socket,
+ sockRef.direction === TO_DRONE ? DRONE_IP : CLIENT_IP,
+ sockRef.port,
+ callbacks.onConnected);
+ } else {
+ callbacks.onConnected(0);
+ }
});
+ } else {
+ chrome.sockets.tcp.create({}, function (sockInfo) {
+ sockRef.socket = sockInfo.socketId;
+ if (sockRef.type == "connect") {
+ chrome.sockets.tcp.connect(sockRef.socket,
+ sockRef.direction === TO_DRONE ? DRONE_IP : CLIENT_IP,
+ sockRef.port,
+ callbacks.onConnected);
+ } else {
+ callbacks.onConnected(0);
+ }
+ });
+ }
}
}
@@ -194,8 +220,13 @@ DRONE.API = (function() {
*/
function disconnect(sockRef) {
if (!SIMULATE) {
- chrome.socket.disconnect(sockRef);
- chrome.socket.destroy(sockRef);
+ if (socketRef.protocol == "udp") {
+ chrome.sockets.udp.close(sockRef.socket);
+ } else {
+ chrome.sockets.tcp.disconnect(sockRef.socket);
+ chrome.sockets.tcp.close(sockRef.socket);
+ }
+ sockRef.socket = null;
}
}
@@ -217,7 +248,7 @@ DRONE.API = (function() {
// send all the commands
if (!SIMULATE) {
- chrome.socket.sendTo(
+ chrome.sockets.udp.send(
atSock.socket,
commandBuffer,
DRONE_IP,
@@ -257,6 +288,37 @@ DRONE.API = (function() {
sendCommands([new DRONE.Command('CONFIG', ['"control:outdoor"', '"'+(outdoor?'TRUE':'FALSE')+'"'])]);
}
+ function onReceiveData(info) {
+ if (info.data.byteLength > 0) {
+ DRONE.NavData.parse(data.data);
+ }
+ }
+
+ function onReceiveDataError(info) {
+ // shutdown();
+ }
+
+ function createListener(socketId, callback) {
+ var boundCallback = callback.bind(this);
+ return function (info) {
+ if (socketId !== info.socketId)
+ return;
+ boudCallback(info);
+ };
+ }
+
+ /**
+ * Sends a keepalive command and attempts to read
+ * back the latest data from the drone
+ */
+ function startReceivingData() {
+ var navSock = sockets['nav'];
+ if (!SIMULATE) {
+ chrome.sockets.udp.onReceive.addListener(createListener(navSock.socketId, onReceiveData));
+ chrome.sockets.udp.onReceiveError.addListener(createListener(navSock.socketId, onReceiveDataError));
+ }
+ }
+
/**
* Sends a keepalive command and attempts to read
* back the latest data from the drone
@@ -264,30 +326,16 @@ DRONE.API = (function() {
function sendKeepAliveCommand() {
var navSock = sockets['nav'];
if (!SIMULATE) {
- chrome.socket.sendTo(
+ chrome.sockets.udp.send(
navSock.socket,
(new Uint8Array([1])).buffer,
DRONE_IP,
navSock.port,
noop);
-
- chrome.socket.read(
- navSock.socket,
- function(data) {
-
- // if we have data parse it
- // otherwise shutdown and call it a day
- if(data.data.byteLength > 0) {
- DRONE.NavData.parse(data.data);
- } else {
- // shutdown();
- }
- });
}
// ensure we call this again
// restore later: setTimeout(sendKeepAliveCommand, 200);
-
}
var takeoffLandStart;
View
29 parrot-ar-drone/manifest.json
@@ -7,18 +7,19 @@
"scripts": ["main.js"]
}
},
- "permissions": [{
- "socket": [
- "udp-bind::5554",
- "udp-send-to::5554",
-
- "tcp-connect:*:5555",
- "tcp-listen:*:5555",
-
- "udp-bind::5556",
- "udp-send-to::5556",
-
- "udp-bind::5559",
- "udp-send-to::5559"]
- }]
+ "permissions": ["system.network"],
+ "sockets": {
+ "udp": {
+ "bind": ":5554",
+ "send": ":5554",
+ "bind": ":5556",
+ "send": ":5556",
+ "bind": ":5559",
+ "send": ":5559",
@mangini Owner
mangini added a note

Is this a valid syntax? Repeated keys in JSON dicts usually means the previous values are replaced, which would make this equivalent to "udp": {"bind": ":5559", "send": ":5559"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ },
+ "tcp": {
+ "connect": "*:5555",
+ "listen": "*:5555",
+ }
+ }
}
View
9 tcpserver/manifest.json
@@ -2,11 +2,16 @@
"manifest_version": 2,
"name": "TCP Server Sample",
"version": "2",
- "minimum_chrome_version": "24",
- "permissions": [ "webview", { "socket" : ["tcp-listen"] } ],
+ "minimum_chrome_version": "33.0.1715.0",
+ "permissions": ["webview", "system.network"],
"app": {
"background": {
"scripts": ["tcp-server.js", "commands/BrowserCommands.js", "main.js"]
}
+ },
+ "sockets": {
+ "tcpServer": {
+ "listen": ""
+ }
}
}
View
92 tcpserver/tcp-server.js
@@ -21,7 +21,7 @@ const DEFAULT_MAX_CONNECTIONS=5;
(function(exports) {
// Define some local variables here.
- var socket = chrome.socket;
+ var socket = chrome.sockets.tcpServer;
/**
* Creates an instance of the client
@@ -35,6 +35,9 @@ const DEFAULT_MAX_CONNECTIONS=5;
this.maxConnections = typeof(options) != 'undefined'
&& options.maxConnections || DEFAULT_MAX_CONNECTIONS;
+ this._onAccept = this._onAccept.bind(this);
+ this._onAcceptError = this._onAcceptError.bind(this);
+
// Callback functions.
this.callbacks = {
listen: null, // Called when socket is connected.
@@ -65,7 +68,7 @@ const DEFAULT_MAX_CONNECTIONS=5;
* preferred network as the addr parameter on TcpServer contructor.
*/
TcpServer.getNetworkAddresses=function(callback) {
- socket.getNetworkList(callback);
+ chrome.system.network.getNetworkInterfaces(callback);
}
TcpServer.prototype.isConnected=function() {
@@ -81,7 +84,7 @@ const DEFAULT_MAX_CONNECTIONS=5;
TcpServer.prototype.listen = function(callback) {
// Register connect callback.
this.callbacks.connect = callback;
- socket.create('tcp', {}, this._onCreate.bind(this));
+ socket.create({}, this._onCreate.bind(this));
};
@@ -91,10 +94,14 @@ const DEFAULT_MAX_CONNECTIONS=5;
* @see http://developer.chrome.com/apps/socket.html#method-disconnect
*/
TcpServer.prototype.disconnect = function() {
- if (this.serverSocketId) socket.disconnect(this.serverSocketId);
+ if (this.serverSocketId) {
+ socket.onAccept.removeListener(this._onAccept);
+ socket.onAcceptError.removeListener(this._onAcceptError);
+ socket.close(this.serverSocketId);
+ }
for (var i=0; i<this.openSockets.length; i++) {
try {
- this.openSockets[i].disconnect();
+ this.openSockets[i].close();
} catch (ex) {
console.log(ex);
}
@@ -115,6 +122,8 @@ const DEFAULT_MAX_CONNECTIONS=5;
TcpServer.prototype._onCreate = function(createInfo) {
this.serverSocketId = createInfo.socketId;
if (this.serverSocketId > 0) {
+ socket.onAccept.addListener(this._onAccept);
+ socket.onAcceptError.addListener(this._onAcceptError);
socket.listen(this.serverSocketId, this.addr, this.port, 50,
this._onListenComplete.bind(this));
this.isListening = true;
@@ -131,41 +140,40 @@ const DEFAULT_MAX_CONNECTIONS=5;
* @private
*/
TcpServer.prototype._onListenComplete = function(resultCode) {
- if (resultCode===0) {
- socket.accept(this.serverSocketId, this._onAccept.bind(this));
- } else {
+ if (resultCode !==0) {
error('Unable to listen to socket. Resultcode='+resultCode);
}
}
- TcpServer.prototype._onAccept = function(resultInfo) {
- // continue to accept other connections:
- socket.accept(this.serverSocketId, this._onAccept.bind(this));
+ TcpServer.prototype._onAccept = function (info) {
+ if (info.socketId != this.serverSocketId)
+ return;
- if (resultInfo.resultCode===0) {
- if (this.openSockets.length>=this.maxConnections) {
- this._onNoMoreConnectionsAvailable(resultInfo.socketId);
- return;
- }
+ if (this.openSockets.length >= this.maxConnections) {
+ this._onNoMoreConnectionsAvailable(info.clientSocketId);
+ return;
+ }
- var tcpConnection = new TcpConnection(resultInfo.socketId);
- this.openSockets.push(tcpConnection);
+ var tcpConnection = new TcpConnection(info.clientSocketId);
+ this.openSockets.push(tcpConnection);
- tcpConnection.requestSocketInfo(this._onSocketInfo.bind(this));
- log('Incoming connection handled.');
+ tcpConnection.requestSocketInfo(this._onSocketInfo.bind(this));
+ log('Incoming connection handled.');
+ }
- } else {
- error('Unable to accept incoming connection. Error code='+resultInfo.resultCode);
- }
+ TcpServer.prototype._onAcceptError = function(info) {
+ if (info.socketId != this.serverSocketId)
+ return;
+ error('Unable to accept incoming connection. Error code=' + info.resultCode);
}
TcpServer.prototype._onNoMoreConnectionsAvailable = function(socketId) {
var msg="No more connections available. Try again later\n";
_stringToArrayBuffer(msg, function(arrayBuffer) {
- socket.write(socketId, arrayBuffer,
+ chrome.sockets.tcp.send(socketId, arrayBuffer,
function() {
- socket.disconnect(socketId);
+ chrome.sockets.tcp.close(socketId);
});
});
}
@@ -195,7 +203,11 @@ const DEFAULT_MAX_CONNECTIONS=5;
log('Established client connection. Listening...');
// Start polling for reads.
- this._onDataRead();
+ this._onReceive = this._onReceive.bind(this);
+ this._onReceiveError = this._onReceiveError.bind(this);
+ chrome.sockets.tcp.onReceive.addListener(this._onReceive);
+ chrome.sockets.tcp.onReceiveError.addListener(this._onReceiveError);
+ chrome.sockets.tcp.setPaused(this.socketId, false);
};
TcpConnection.prototype.setSocketInfo = function(socketInfo) {
@@ -203,7 +215,7 @@ const DEFAULT_MAX_CONNECTIONS=5;
};
TcpConnection.prototype.requestSocketInfo = function(callback) {
- socket.getInfo(this.socketId,
+ chrome.sockets.tcp.getInfo(this.socketId,
this._onSocketInfo.bind(this, callback));
};
@@ -227,7 +239,7 @@ const DEFAULT_MAX_CONNECTIONS=5;
*/
TcpConnection.prototype.sendMessage = function(msg, callback) {
_stringToArrayBuffer(msg + '\n', function(arrayBuffer) {
- socket.write(this.socketId, arrayBuffer, this._onWriteComplete.bind(this));
+ chrome.sockets.tcp.send(this.socketId, arrayBuffer, this._onWriteComplete.bind(this));
}.bind(this));
// Register sent callback.
@@ -240,8 +252,12 @@ const DEFAULT_MAX_CONNECTIONS=5;
*
* @see http://developer.chrome.com/apps/socket.html#method-disconnect
*/
- TcpConnection.prototype.disconnect = function() {
- if (this.socketId) socket.disconnect(this.socketId);
+ TcpConnection.prototype.close = function() {
+ if (this.socketId) {
+ chrome.sockets.tcp.onReceive.removeListener(this._onReceive);
+ chrome.sockets.tcp.onReceiveError.removeListener(this._onReceiveError);
+ chrome.sockets.tcp.close(this.socketId);
+ }
};
@@ -277,23 +293,23 @@ const DEFAULT_MAX_CONNECTIONS=5;
* @see TcpConnection.prototype.addDataReceivedListener
* @param {Object} readInfo The incoming message
*/
- TcpConnection.prototype._onDataRead = function(readInfo) {
- // Any read error is considered a disconnect from the remote host.
- // Disconnect our socket in that case.
- if (readInfo && readInfo.resultCode < 0) {
- this.disconnect();
+ TcpConnection.prototype._onReceive = function(info) {
+ if (this.socketId != info.socketId)
return;
- }
// Call received callback if there's data in the response.
if (this.callbacks.recv) {
log('onDataRead');
// Convert ArrayBuffer to string.
- _arrayBufferToString(readInfo.data, this.callbacks.recv.bind(this));
+ _arrayBufferToString(info.data, this.callbacks.recv.bind(this));
}
- socket.read(this.socketId, null, this._onDataRead.bind(this));
};
+ TcpConnection.prototype._onReceiveError = function (info) {
+ if (this.socketId != info.socketId)
+ return;
+ this.close();
+ };
/**
* Callback for when data has been successfully
View
12 telnet/manifest.json
@@ -2,7 +2,7 @@
"name": "Telnet Client",
"version": "2",
"manifest_version": 2,
- "minimum_chrome_version": "23",
+ "minimum_chrome_version": "33.0.1715.0",
"icons": {
"128": "icon_128.png"
},
@@ -11,9 +11,9 @@
"scripts": ["launch.js"]
}
},
- "permissions": [
- {"socket": [
- "tcp-connect:*:*"
- ]}
- ]
+ "sockets": {
+ "tcp": {
+ "connect": "*:*"
+ }
+ }
}
View
92 telnet/tcp-client.js
@@ -19,7 +19,7 @@ Author: Boris Smus (smus@chromium.org)
(function(exports) {
// Define some local variables here.
- var socket = chrome.socket;
+ var socket = chrome.sockets.tcp;
/**
* Creates an instance of the client
@@ -30,6 +30,8 @@ Author: Boris Smus (smus@chromium.org)
function TcpClient(host, port) {
this.host = host;
this.port = port;
+ this._onReceive = this._onReceive.bind(this);
+ this._onReceiveError = this._onReceiveError.bind(this);
// Callback functions.
this.callbacks = {
@@ -49,20 +51,20 @@ Author: Boris Smus (smus@chromium.org)
/**
* Connects to the TCP socket, and creates an open socket.
*
- * @see http://developer.chrome.com/apps/socket.html#method-create
+ * @see http://developer.chrome.com/apps/sockets_tcp.html#method-create
* @param {Function} callback The function to call on connection
*/
TcpClient.prototype.connect = function(callback) {
// Register connect callback.
this.callbacks.connect = callback;
- socket.create('tcp', {}, this._onCreate.bind(this));
+ socket.create({}, this._onCreate.bind(this));
};
/**
* Sends a message down the wire to the remote side
*
- * @see http://developer.chrome.com/apps/socket.html#method-write
+ * @see http://developer.chrome.com/apps/sockets_tcp.html#method-send
* @param {String} msg The message to send
* @param {Function} callback The function to call when the message has sent
*/
@@ -71,7 +73,7 @@ Author: Boris Smus (smus@chromium.org)
this.callbacks.sent = callback;
this._stringToArrayBuffer(msg + '\n', function(arrayBuffer) {
- socket.write(this.socketId, arrayBuffer, this._onWriteComplete.bind(this));
+ socket.send(this.socketId, arrayBuffer, this._onSendComplete.bind(this));
}.bind(this));
};
@@ -88,10 +90,14 @@ Author: Boris Smus (smus@chromium.org)
/**
* Disconnects from the remote side
*
- * @see http://developer.chrome.com/apps/socket.html#method-disconnect
+ * @see http://developer.chrome.com/apps/sockets_tcp.html#method-disconnect
*/
- TcpClient.prototype.disconnect = function() {
+ TcpClient.prototype.disconnect = function () {
+ socket.onReceive.removeListener(this._onReceive);
+ socket.onReceiveError.removeListener(this._onReceiveError);
socket.disconnect(this.socketId);
+ socket.close(this.socketId);
+ this.socketId = null;
this.isConnected = false;
};
@@ -101,17 +107,17 @@ Author: Boris Smus (smus@chromium.org)
* we go ahead and connect to the remote side.
*
* @private
- * @see http://developer.chrome.com/apps/socket.html#method-connect
+ * @see http://developer.chrome.com/apps/sockets_tcp.html#method-connect
* @param {Object} createInfo The socket details
*/
- TcpClient.prototype._onCreate = function(createInfo) {
- this.socketId = createInfo.socketId;
- if (this.socketId > 0) {
- socket.connect(this.socketId, this.host, this.port, this._onConnectComplete.bind(this));
- this.isConnected = true;
- } else {
- error('Unable to create socket');
+ TcpClient.prototype._onCreate = function (createInfo) {
+ if (chrome.runtime.lastError) {
+ error('Unable to create socket: ' + chrome.runtime.lastError.message);
}
+
+ this.socketId = createInfo.socketId;
+ this.isConnected = true;
+ socket.connect(this.socketId, this.host, this.port, this._onConnectComplete.bind(this));
};
/**
@@ -122,9 +128,15 @@ Author: Boris Smus (smus@chromium.org)
* @private
* @param {Number} resultCode Indicates whether the connection was successful
*/
- TcpClient.prototype._onConnectComplete = function(resultCode) {
- // Start polling for reads.
- setInterval(this._periodicallyRead.bind(this), 500);
+ TcpClient.prototype._onConnectComplete = function (resultCode) {
+ if (resultCode < 0) {
+ error('Unable to connect to server');
+ return;
+ }
+
+ // Start listening to message events.
+ socket.onReceive.addListener(this._onReceive);
+ socket.onReceiveError.addListener(this._onReceiveError);
if (this.callbacks.connect) {
console.log('connect complete');
@@ -134,27 +146,22 @@ Author: Boris Smus (smus@chromium.org)
};
/**
- * Checks for new data to read from the socket
- *
- * @see http://developer.chrome.com/apps/socket.html#method-read
- */
- TcpClient.prototype._periodicallyRead = function() {
- socket.read(this.socketId, this._onDataRead.bind(this));
- };
-
- /**
* Callback function for when data has been read from the socket.
* Converts the array buffer that is read in to a string
* and sends it on for further processing by passing it to
* the previously assigned callback function.
*
+ * @see http://developer.chrome.com/apps/sockets_tcp.html#event-onReceive
+ *
* @private
* @see TcpClient.prototype.addResponseListener
* @param {Object} readInfo The incoming message
*/
- TcpClient.prototype._onDataRead = function(readInfo) {
- // Call received callback if there's data in the response.
- if (readInfo.resultCode > 0 && this.callbacks.recv) {
+ TcpClient.prototype._onReceive = function (readInfo) {
+ if (readInfo.socketId != this.socketId)
+ return;
+
+ if (this.callbacks.recv) {
log('onDataRead');
// Convert ArrayBuffer to string.
this._arrayBufferToString(readInfo.data, function(str) {
@@ -164,17 +171,32 @@ Author: Boris Smus (smus@chromium.org)
};
/**
+ * Callback function for an error occurs on the socket.
+ *
+ * @see http://developer.chrome.com/apps/sockets_tcp.html#event-onReceiveError
+ *
+ * @private
+ * @param {Object} info The incoming message
+ */
+ TcpClient.prototype._onReceiveError = function (info) {
+ if (info.socketId != this.socketId)
+ return;
+
+ error('Unable to receive data from socket: ' + info.resultCode);
+ };
+
+ /**
* Callback for when data has been successfully
- * written to the socket.
+ * sent to the socket.
*
* @private
- * @param {Object} writeInfo The outgoing message
+ * @param {Object} sendInfo The outgoing message
*/
- TcpClient.prototype._onWriteComplete = function(writeInfo) {
- log('onWriteComplete');
+ TcpClient.prototype._onSendComplete = function(sendInfo) {
+ log('onSendComplete');
// Call sent callback.
if (this.callbacks.sent) {
- this.callbacks.sent(writeInfo);
+ this.callbacks.sent(sendInfo);
}
};
View
14 udp/manifest.json
@@ -3,16 +3,16 @@
"name": "Sample of UDP Network Access",
"description": "Echo..... Echo.",
"version": "2",
@mangini Owner
mangini added a note

Please, bump the version of all modified samples, so they can be updated in CWS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
- "minimum_chrome_version": "23",
+ "minimum_chrome_version": "33.0.1715.0",
"app": {
"background": {
"scripts": ["main.js"]
}
},
- "permissions": [
- "experimental",
- {"socket": [
- "udp-send-to"
- ]}
- ]
+ "sockets": {
+ "udp": {
+ "bind": "",
+ "send": ""
+ }
+ }
}
View
49 udp/networking.js
@@ -4,53 +4,49 @@
var NoAddressException = "No Address";
var NotConnectedException = "Not Connected";
- var socket = chrome.socket || chrome.experimental.socket;
+ var socket = chrome.sockets.udp;
- var baseClient = function(socketMode) {
+ var baseClient = function() {
var address;
+ var port;
var socketInfo;
var connected = false;
var callbacks = [];
var self = this;
- this.connect = function(inAddress, port, callback, responseHandler) {
+ this.connect = function(inAddress, inPort, callback, responseHandler) {
if(!!inAddress == false) throw NoAddressException;
address = inAddress;
- port = port || this.defaultPort;
- console.debug('creating socket', socketMode, address, port);
- socket.create(socketMode, {}, function(_socketInfo) {
+ port = inPort || this.defaultPort;
+ console.debug('creating socket', address, port);
+ socket.create({}, function(_socketInfo) {
socketInfo = _socketInfo;
- socket.connect(socketInfo.socketId, address, port, function(connectResult) {
- console.debug('connectResult', connectResult);
- connected = (connectResult == 0);
+ socket.bind(socketInfo.socketId, "0.0.0.0", 0, function(bindResult) {
+ console.debug('bindResult', bindResult);
+ connected = (bindResult == 0);
socket.ondata = function(result) {
if (callbacks.length > 0) {
callbacks.shift()(result);
}
};
- self.poll();
+ socket.onReceive.addListener(this._onReceive);
callback(connected);
});
});
};
- this.poll = function() {
- if(!!address == false) throw NoAddressException;
- if(connected == false) throw NotConnectedException;
- socket.read(socketInfo.socketId, (function(result) {
- if (result.resultCode > 0) {
- socket.ondata(result);
- }
- this.poll();
- }).bind(this));
- };
+ this._onReceive = function(info) {
+ if (info.socketId != socketInfo.socketId)
+ return;
+ socket.ondata(info);
+ }.bind(this);
this.send = function(data, callback) {
callback = callback || function() {};
if(!!address == false) throw NoAddressException;
if(connected == false) throw NotConnectedException;
- socket.write(socketInfo.socketId, data, function(sendResult) {
+ socket.send(socketInfo.socketId, data, address, port, function (sendResult) {
callback(sendResult);
});
};
@@ -64,15 +60,16 @@
this.disconnect = function() {
if(!!address == false) throw NoAddressException;
if(connected == false) throw NotConnectedException;
- socket.disconnect(socketInfo.socketId);
- socket.destroy(socketInfo.socketId);
+ socket.onReceive.removeListener(this._onReceive);
+ socket.close(socketInfo.socketId);
+ socketInfo = null;
connected = false;
};
};
- var _EchoClient = function(socketMode, defaultPort) {
+ var _EchoClient = function(defaultPort) {
return function() {
- var client = new baseClient(socketMode);
+ var client = new baseClient();
this.defaultPort = defaultPort;
this.connect = client.connect;
@@ -107,7 +104,7 @@
// Clients
clients: {
udp: {
- echoClient: _EchoClient('udp', 7)
+ echoClient: _EchoClient(7)
}
},
// Exceptions
View
135 webserver/index.js
@@ -5,9 +5,11 @@ onload = function() {
var port = document.getElementById("port");
var directory = document.getElementById("directory");
- var socket = chrome.socket;
+ var socket = chrome.sockets.tcpServer;
+ var clientSocket = chrome.sockets.tcp;
var socketInfo;
var filesMap = {};
+ var clientSocketIds = {};
var stringToUint8Array = function(string) {
var buffer = new ArrayBuffer(string.length);
@@ -40,16 +42,13 @@ onload = function() {
var header = stringToUint8Array("HTTP/1.0 " + errorCode + " Not Found\nContent-length: " + file.size + "\nContent-type:" + contentType + ( keepAlive ? "\nConnection: keep-alive" : "") + "\n\n");
console.info("writeErrorResponse:: Done setting header...");
var outputBuffer = new ArrayBuffer(header.byteLength + file.size);
- var view = new Uint8Array(outputBuffer)
+ var view = new Uint8Array(outputBuffer);
view.set(header, 0);
console.info("writeErrorResponse:: Done setting view...");
- socket.write(socketId, outputBuffer, function(writeInfo) {
+ clientSocket.send(socketId, outputBuffer, function(writeInfo) {
console.log("WRITE", writeInfo);
- if (keepAlive) {
- readFromSocket(socketId);
- } else {
- socket.destroy(socketId);
- socket.accept(socketInfo.socketId, onAccept);
+ if (!keepAlive) {
+ closeClientSocket(socketId);
}
});
console.info("writeErrorResponse::filereader:: end onload...");
@@ -62,19 +61,16 @@ onload = function() {
var contentLength = file.size;
var header = stringToUint8Array("HTTP/1.0 200 OK\nContent-length: " + file.size + "\nContent-type:" + contentType + ( keepAlive ? "\nConnection: keep-alive" : "") + "\n\n");
var outputBuffer = new ArrayBuffer(header.byteLength + file.size);
- var view = new Uint8Array(outputBuffer)
+ var view = new Uint8Array(outputBuffer);
view.set(header, 0);
var fileReader = new FileReader();
fileReader.onload = function(e) {
view.set(new Uint8Array(e.target.result), header.byteLength);
- socket.write(socketId, outputBuffer, function(writeInfo) {
+ clientSocket.send(socketId, outputBuffer, function(writeInfo) {
console.log("WRITE", writeInfo);
- if (keepAlive) {
- readFromSocket(socketId);
- } else {
- socket.destroy(socketId);
- socket.accept(socketInfo.socketId, onAccept);
+ if (!keepAlive) {
+ closeClientSocket(socketId);
}
});
};
@@ -82,50 +78,73 @@ onload = function() {
fileReader.readAsArrayBuffer(file);
};
+ var addClientSocket = function(socketId) {
+ clientSocketIds[socketId] = socketId;
+ clientSocket.setPaused(socketId, false);
+ };
+
+ var closeClientSocket = function(socketId) {
+ delete clientSocketIds[socketId];
+ clientSocket.close(socketId);
+ };
+
var onAccept = function(acceptInfo) {
- console.log("ACCEPT", acceptInfo)
- readFromSocket(acceptInfo.socketId);
+ console.log("ACCEPT", acceptInfo);
+ addClientSocket(acceptInfo.clientSocketId);
};
- var readFromSocket = function(socketId) {
- // Read in the data
- socket.read(socketId, function(readInfo) {
- console.log("READ", readInfo);
- // Parse the request.
- var data = arrayBufferToString(readInfo.data);
- if(data.indexOf("GET ") == 0) {
- var keepAlive = false;
- if (data.indexOf("Connection: keep-alive") != -1) {
- keepAlive = true;
- }
-
- // we can only deal with GET requests
- var uriEnd = data.indexOf(" ", 4);
- if(uriEnd < 0) { /* throw a wobbler */ return; }
- var uri = data.substring(4, uriEnd);
- // strip qyery string
- var q = uri.indexOf("?");
- if (q != -1) {
- uri = uri.substring(0, q);
- }
- var file = filesMap[uri];
- if(!!file == false) {
- console.warn("File does not exist..." + uri);
- writeErrorResponse(socketId, 404, keepAlive);
- return;
- }
- logToScreen("GET 200 " + uri);
- write200Response(socketId, file, keepAlive);
+ var onReceive = function(readInfo) {
+ if (clientSocketIds[readInfo.socketId] !== readInfo.socketId)
+ return;
+
+ var socketId = readInfo.socketId;
+ console.log("READ", readInfo);
+ // Parse the request.
+ var data = arrayBufferToString(readInfo.data);
+ if (data.indexOf("GET ") == 0) {
+ var keepAlive = false;
+ if (data.indexOf("Connection: keep-alive") != -1) {
+ keepAlive = true;
+ }
+
+ // we can only deal with GET requests
+ var uriEnd = data.indexOf(" ", 4);
+ if (uriEnd < 0) { /* throw a wobbler */ return; }
+ var uri = data.substring(4, uriEnd);
+ // strip qyery string
+ var q = uri.indexOf("?");
+ if (q != -1) {
+ uri = uri.substring(0, q);
}
- else {
- // Throw an error
- socket.destroy(socketId);
+ var file = filesMap[uri];
+ if (!!file == false) {
+ console.warn("File does not exist..." + uri);
+ writeErrorResponse(socketId, 404, keepAlive);
+ return;
}
- });
+ logToScreen("GET 200 " + uri);
+ write200Response(socketId, file, keepAlive);
+ }
+ else {
+ // Throw an error
+ closeClientSocket(socketId);
+ }
+ };
+
+ var onReceiveError = function(readInfo) {
+ if (clientSocketIds[readInfo.socketId] !== readInfo.socketId)
+ return;
+
+ var socketId = readInfo.socketId;
+ console.log("READ ERROR", readInfo);
+ closeClientSocket(socketId);
};
directory.onchange = function(e) {
- if (socketInfo) socket.destroy(socketInfo.socketId);
+ if (socketInfo) {
+ socket.close(socketInfo.socketId);
+ socketInfo = null;
+ }
var files = e.target.files;
@@ -145,11 +164,10 @@ onload = function() {
};
start.onclick = function() {
- socket.create("tcp", {}, function(_socketInfo) {
+ socket.create({}, function(_socketInfo) {
socketInfo = _socketInfo;
socket.listen(socketInfo.socketId, hosts.value, parseInt(port.value), 50, function(result) {
console.log("LISTENING:", result);
- socket.accept(socketInfo.socketId, onAccept);
});
});
@@ -162,10 +180,13 @@ onload = function() {
directory.disabled = false;
stop.disabled = true;
start.disabled = false;
- socket.destroy(socketInfo.socketId);
+ if (socketInfo) {
+ socket.close(socketInfo.socketId);
+ socketInfo = null;
+ }
};
- socket.getNetworkList(function(interfaces) {
+ chrome.system.network.getNetworkInterfaces(function(interfaces) {
for(var i in interfaces) {
var interface = interfaces[i];
var opt = document.createElement("option");
@@ -174,4 +195,8 @@ onload = function() {
hosts.appendChild(opt);
}
});
+
+ socket.onAccept.addListener(onAccept);
+ clientSocket.onReceive.addListener(onReceive);
+ clientSocket.onReceiveError.addListener(onReceiveError);
};
View
11 webserver/manifest.json
@@ -3,6 +3,7 @@
"version": "3",
"manifest_version": 2,
"description": "__MSG_appDescription__",
+ "minimum_chrome_version": "33.0.1715.0",
"icons": {
"16": "icon-16.png",
"128": "icon-128.png"
@@ -13,5 +14,13 @@
"scripts": ["main.js"]
}
},
- "permissions": [{"socket":["tcp-connect", "tcp-listen"]}]
+ "permissions": ["system.network"],
+ "sockets": {
+ "tcp":{
+ "connect": ""
+ },
+ "tcpServer": {
+ "listen": ""
+ }
+ }
}
View
3  websocket-server/README.md
@@ -7,7 +7,8 @@ An example Http and WebSocket server implementation with a sample app which serv
## APIs
-* [chrome.socket](http://developer.chrome.com/apps/socket.html)
+* [chrome.sockets.tcpServer](http://developer.chrome.com/apps/sockets.tcpServer.html)
+* [chrome.sockets.tcp](http://developer.chrome.com/apps/sockets.tcp.html)
* [Runtime](http://developer.chrome.com/apps/app.runtime.html)
* [Window](http://developer.chrome.com/apps/app.window.html)
View
154 websocket-server/http.js
@@ -6,12 +6,7 @@
var http = function() {
-var socket = (chrome.experimental && chrome.experimental.socket) ||
- chrome.socket;
-
-// If this does not have chrome.socket, then return an empty http namespace.
-if (!socket)
- return {};
+var clientSockets = {};
// Http response code strings.
var responseMap = {
@@ -122,7 +117,14 @@ EventSource.prototype = {
*/
function HttpServer() {
EventSource.apply(this);
+ this.acceptConnection_ = this.acceptConnection_.bind(this);
+ this.onReceive_ = this.onReceive_.bind(this);
+ this.onReceiveError_ = this.onReceiveError_.bind(this);
this.readyState_ = 0;
+
+ chrome.sockets.tcpServer.onAccept.addListener(this.acceptConnection_);
+ chrome.sockets.tcp.onReceive.addListener(this.onReceive_);
+ chrome.sockets.tcp.onReceiveErrror.addListener(this.onReceiveError_);
}
HttpServer.prototype = {
@@ -137,64 +139,70 @@ HttpServer.prototype = {
*/
listen: function(port, opt_host) {
var t = this;
- socket.create('tcp', {}, function(socketInfo) {
+ chrome.sockets.tcpServer.create({}, function (socketInfo) {
t.socketInfo_ = socketInfo;
- socket.listen(t.socketInfo_.socketId, opt_host || '0.0.0.0', port, 50,
+ chrome.sockets.tcpServer.listen(t.socketInfo_.socketId, opt_host || '0.0.0.0', port, 50,
function(result) {
t.readyState_ = 1;
- t.acceptConnection_(t.socketInfo_.socketId);
});
});
},
acceptConnection_: function(socketId) {
- var t = this;
- socket.accept(this.socketInfo_.socketId, function(acceptInfo) {
- t.onConnection_(acceptInfo);
- t.acceptConnection_(socketId);
- });
+ t.onConnection_(acceptInfo);
},
onConnection_: function(acceptInfo) {
- this.readRequestFromSocket_(acceptInfo.socketId);
+ var socketId = acceptInfo.clientSocketId;
+ this.addClientSocket_(socketId);
+ chrome.sockets.tcp.setPaused(socketId, false);
+ this.readRequestFromSocket_(socketId);
},
- readRequestFromSocket_: function(socketId) {
- var t = this;
- var requestData = '';
- var endIndex = 0;
- var onDataRead = function(readInfo) {
- // Check if connection closed.
- if (readInfo.resultCode <= 0) {
- socket.disconnect(socketId);
- socket.destroy(socketId);
- return;
- }
- requestData += arrayBufferToString(readInfo.data).replace(/\r\n/g, '\n');
- // Check for end of request.
- endIndex = requestData.indexOf('\n\n', endIndex);
- if (endIndex == -1) {
- endIndex = requestData.length - 1;
- socket.read(socketId, onDataRead);
- return;
- }
+ addClientSocket_: function(socketId) {
+ clientSockets[socketId] = { requestData: '', endIndex: 0 };
+ },
- var headers = requestData.substring(0, endIndex).split('\n');
- var headerMap = {};
- // headers[0] should be the Request-Line
- var requestLine = headers[0].split(' ');
- headerMap['method'] = requestLine[0];
- headerMap['url'] = requestLine[1];
- headerMap['Http-Version'] = requestLine[2];
- for (var i = 1; i < headers.length; i++) {
- requestLine = headers[i].split(':', 2);
- if (requestLine.length == 2)
- headerMap[requestLine[0]] = requestLine[1].trim();
- }
- var request = new HttpRequest(headerMap, socketId);
- t.onRequest_(request);
+ closeClientSocket_: function(socketId) {
+ chrome.sockets.tcp.close(socketId);
+ delete clientSockets[socketId];
+ },
+
+ onReceive_: function(readInfo) {
+ var socketId = readInfo.socketId;
+ if (!clientSockets[socketId])
+ return;
+
+ clientSockets[socketId].requestData += arrayBufferToString(readInfo.data).replace(/\r\n/g, '\n');
+ // Check for end of request.
+ clientSockets[socketId].endIndex = clientSockets[socketId].requestData.indexOf('\n\n', endIndex);
+ if (clientSockets[socketId].endIndex == -1) {
+ clientSockets[socketId].endIndex = clientSockets[socketId].requestData.length - 1;
+ return;
+ }
+
+ var headers = clientSockets[socketId].requestData.substring(0, endIndex).split('\n');
+ var headerMap = {};
+ // headers[0] should be the Request-Line
+ var requestLine = headers[0].split(' ');
+ headerMap['method'] = requestLine[0];
+ headerMap['url'] = requestLine[1];
+ headerMap['Http-Version'] = requestLine[2];
+ for (var i = 1; i < headers.length; i++) {
+ requestLine = headers[i].split(':', 2);
+ if (requestLine.length == 2)
+ headerMap[requestLine[0]] = requestLine[1].trim();
}
- socket.read(socketId, onDataRead);
+ var request = new HttpRequest(headerMap, socketId);
+ t.onRequest_(request);
+ },
+
+ onReceiveError_: function (readInfo) {
+ var socketId = readInfo.socketId;
+ if (!clientSockets[socketId])
+ return;
+
+ this.closeClientSocket_(socketId);
},
onRequest_: function(request) {
@@ -202,8 +210,8 @@ HttpServer.prototype = {
var keepAlive = request.headers['Connection'] == 'keep-alive';
if (!this.dispatchEvent(type, request))
request.close();
- else if (keepAlive)
- this.readRequestFromSocket_(request.socketId_);
+ else if (!keepAlive)
+ this.closeClientSocket_(request.socketId_);
},
};
@@ -248,8 +256,7 @@ HttpRequest.prototype = {
// The socket for keep alive connections will be re-used by the server.
// Just stop referencing or using the socket in this HttpRequest.
if (this.headers['Connection'] != 'keep-alive') {
- socket.disconnect(this.socketId_);
- socket.destroy(this.socketId_);
+ chrome.sockets.tcp.close(this.socketId_);
}
this.socketId_ = 0;
this.readyState = 3;
@@ -352,12 +359,12 @@ HttpRequest.prototype = {
write_: function(array) {
var t = this;
this.bytesRemaining += array.byteLength;
- socket.write(this.socketId_, array, function(writeInfo) {
- if (writeInfo.bytesWritten < 0) {
- console.error('Error writing to socket, code '+writeInfo.bytesWritten);
+ chrome.sockets.tcp.send(this.socketId_, array, function (writeInfo) {
+ if (writeInfo.bytesSent < 0) {
+ console.error('Error writing to socket, code ' + writeInfo.bytesSent);
return;
}
- t.bytesRemaining -= writeInfo.bytesWritten;
+ t.bytesRemaining -= writeInfo.bytesSent;
t.checkFinished_();
});
},
@@ -475,6 +482,8 @@ WebSocketRequest.prototype = {
function WebSocketServerSocket(socketId) {
this.socketId_ = socketId;
EventSource.apply(this);
+ this.onReceive_ = this.onReceive_.bind(this);
+ this.onReceiveError_ = this.onReceiveError_.bind(this);
this.readFromSocket_();
}
@@ -506,15 +515,16 @@ WebSocketServerSocket.prototype = {
var fragmentedOp = 0;
var fragmentedMessage = '';
- var onDataRead = function(readInfo) {
- if (readInfo.resultCode <= 0) {
- t.close_();
+ var onDataReadError = function (readInfo) {
+ if (t.socketId !== readInfo.socketId)
return;
- }
- if (!readInfo.data.byteLength) {
- socket.read(t.socketId_, onDataRead);
+
+ t.close_();
+ };
+
+ var onDataRead = function(readInfo) {
+ if (t.socketId !== readInfo.socketId)
return;
- }
var a = new Uint8Array(readInfo.data);
for (var i = 0; i < a.length; i++)
@@ -576,9 +586,11 @@ WebSocketServerSocket.prototype = {
break; // Insufficient data, wait for more.
}
}
- socket.read(t.socketId_, onDataRead);
};
- socket.read(this.socketId_, onDataRead);
+
+ chrome.sockets.tcp.onReceive.addListener(onDataRead);
+ chrome.sockets.tcp.onReceiveError.addListener(onDataReadError);
+ chrome.sockets.tcp.setPaused(this.socketId, false);
},
onFrame_: function(op, data) {
@@ -629,17 +641,17 @@ WebSocketServerSocket.prototype = {
}
var array = WebsocketFrameString(op, data || '');
- socket.write(this.socketId_, array, function(writeInfo) {
- if (writeInfo.resultCode < 0 ||
- writeInfo.bytesWritten !== array.byteLength) {
+ chrome.sockets.tcp.send(this.socketId_, array, function(sendInfo) {
+ if (sendInfo.resultCode < 0 ||
+ sendInfo.bytesSent !== array.byteLength) {
t.close_();
}
});
},
close_: function() {
- chrome.socket.disconnect(this.socketId_);
- chrome.socket.destroy(this.socketId_);
+ chrome.sockets.tcp.disconnect(this.socketId_);
+ chrome.sockets.tcp.close(this.socketId_);
this.readyState = 3;
this.dispatchEvent('close');
}
Something went wrong with that request. Please try again.