Created
April 29, 2011 19:40
-
-
Save rusticphilosopher/948889 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Create a socket, connect to another listening socket locally, write some data and then enter read loop | |
var connectSocket = Ti.Network.Socket.createTCP({ | |
host: 'google.com', | |
port: 80, | |
connected: function(e) { | |
Ti.API.info("Socket <" + e.socket + "> connected to host <" + e.socket.host + ">"); | |
postConnect(); | |
}, | |
error: function(e) { | |
Ti.API.error("Socket <" + e.socket + "> encountered error when connecting"); | |
Ti.API.error(" error code <" + e.errorCode + ">"); | |
Ti.API.error(" error description <" + e.error + ">"); | |
} | |
}); | |
connectSocket.connect(); | |
function postConnect() | |
{ | |
try { | |
// write some data | |
var outData = Ti.createBuffer({value:"Howdy remote socket! How are you?"}); | |
var bytesWritten = connectSocket.write(outData); | |
Ti.API.info("<" + bytesWritten + "> bytes written to socket"); | |
// start read loop | |
var readBuffer = Ti.createBuffer({length:1024}); | |
var bytesRead = 0; | |
while ((bytesRead = connectSocket.read(readBuffer)) > -1) { | |
var stringData = Ti.Codec.decodeString({source: readBuffer, length: bytesRead }); | |
Ti.API.info("received <" + bytesRead + "> bytes of data. String representation of data is <" + stringData + ">"); | |
readBuffer.clear(); // clear the buffer before the next read | |
} | |
Ti.API.info("socket has closed"); | |
connectSocket.close(); // close the socket on our end | |
} catch (e) { | |
// IO error on socket. socket is closed and connectSocket.error is called | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment