Skip to content

Instantly share code, notes, and snippets.

@KensakuKOMATSU
Created September 28, 2012 11:32
Show Gist options
  • Save KensakuKOMATSU/3799303 to your computer and use it in GitHub Desktop.
Save KensakuKOMATSU/3799303 to your computer and use it in GitHub Desktop.
chrome packaged apps v2 (tcp server)
/**
* manifest.json(server)
*/
{
"manifest_version": 2,
"name": "tcp socket server sample",
"description": "try tcp socket server coding!!",
"version": "0.1",
"minimum_chrome_version": "24",
"app": {
"background": {
"scripts": ["server.js"]
}
},
"permissions": [
"experimental",
{"socket": [
"tcp-listen"
]}
]
}
/*
* server.js
*/
function t2ab(str /* String */) {
var buffer = new ArrayBuffer(str.length);
var view = new DataView(buffer);
for(var i = 0, l = str.length; i < l; i++) {
view.setInt8(i, str.charAt(i).charCodeAt());
}
return buffer;
}
function ab2t(buffer /* ArrayBuffer */) {
var arr = new Int8Array(buffer);
var str = "";
for(var i = 0, l = arr.length; i < l; i++) {
str += String.fromCharCode.call(this, arr[i]);
}
return str;
}
/*
chrome.socket.getInfo(s.socketId, function(e){
console.dir(e); // you can check listen port :)
});
*/
chrome.socket.create('tcp', {}, function(e){
var s = e;
chrome.socket.listen(s.socketId, "0.0.0.0", 0, 10, function(e){
chrome.socket.accept(s.socketId, function(e){
var s_ = e.socketId;
chrome.socket.read(s_, 1024, function(e){
chrome.socket.write(s_, e.data, function(e){
});
})
});
});
});
/**
* to http server ...
*/
var CRLF = "\r\n";
var RESPHEAD = [
"HTTP/1.1 200 OK",
"Server: chrome24",
"Content-Length: {%len%}",
"Connection: Close",
"Content-Type: text/html",
"",
""
]
RESPHEAD = RESPHEAD.join(CRLF);
var RESP = [
"<!doctype html>",
"<html>",
"<head>",
"</head>",
"<body>",
"<h1>Welcome!!</h1>",
"<p>this web server is built w/ chrome's packaged apps v2 feature</p>",
"</body>",
"</html>"
]
RESP = RESP.join(CRLF);
chrome.socket.write(s_, ?????????, function(e){});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment