Skip to content

Instantly share code, notes, and snippets.

@coomsie

coomsie/gist:1156622

Created Aug 19, 2011
Embed
What would you like to do?
Titanium web server using sockets - but has issues
///create listener to send tiles
var connectedSockets = [];
var acceptedCallbacks = {
error : function(e) {
Ti.UI.createAlertDialog({
title:"Socket error: "+e.socket.host,
message:e.error
}).show();
removeSocket(e.socket);
}
};
///Ti.Platform.address,
var socket = Titanium.Network.Socket.createTCP({
host:Ti.Platform.address,
port:40404,
accepted: function(e) {
var sock = e.inbound;
connectedSockets.push(sock);
Ti.API.info('ACCEPTED: '+sock.host+':'+sock.port);
socket.accept(acceptedCallbacks);
Ti.Stream.pump(sock, pumpCallback, 1024, true);
},
closed: function(e) {
Ti.API.info("Closed listener");
},
error: function(e) {
Ti.UI.createAlertDialog({
title:"Listener error: "+e.errorCode,
message:e.error
}).show();
}
});
socket.listen();
Ti.API.info( "Listening on "+socket.host+":"+socket.port);
socket.accept(acceptedCallbacks);
function write(){
///write something
var plBlob = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'tile.png').read();
var input = Ti.Stream.createStream({source:plBlob, mode:Ti.Stream.MODE_READ});
for (var index in connectedSockets) {
var sock = connectedSockets[index];
Ti.Stream.writeStream(input, sock, 4096);
}
};
function removeSocket(sock) {
var index = connectedSockets.indexOf(sock);
if (index != -1) {
connectedSockets.splice(index,1);
}
}
function pumpCallback(e) {
if (e.bytesProcessed == -1) { // EOF
Ti.API.info("<EOF> - Closing the remote socket!");
e.source.close();
removeSocket(e.source);
}
else if (e.errorDescription == null || e.errorDescription == "") {
//geting data here ....... ? then send data from request .....
var msg = "HTTP/1.1 200 OK\n";
msg += "Date: Fri, 31 Dec 1999 23:59:59 GMT\n";
msg += "Connection: close\n";
msg += "Content-Type: text/html\n";
msg += "Content-Length: 56\n";
msg += "\n";
msg += "<html><body><h1>Happy New Millennium!</h1></body></html>";
for (var index in connectedSockets) {
var sock = connectedSockets[index];
sock.write(Ti.createBuffer({value: msg}));
sock.close;
}
//connectedSockets[0].write(Ti.createBuffer({value: msg}));
}
else {
Ti.API.info("READ ERROR: "+e.errorDescription);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment