Ti.Network.TCPSocket not returning anything - tidesdk

I am trying to use Ti.Network.TCPSocket to login to an IMAP server.
Its hard as I am not receiving anything back to debug with. For example:
var socket = Ti.Network.createTCPSocket("imap.gmail.com", 993);
socket.connect();
socket.write("LOGIN user pass\r\n");
//event handlers
socket.onWrite(function(data) {
Ti.API.debug('Written to socket: '+data);
});
socket.onError(function(data) {
Ti.API.debug(data);
});
I am not getting anything back. Not even an error or some sort of code or acknowledgement that something is actually happening.
Am I doing something wrong here?
How can I get these even handlers to work or the socket to return some sort of message.
Any help would be appreciated.
UPDATE - Full Code
Ti.API.debug('Start A socket Connection');
var socket = Ti.Network.createTCPSocket("imap.gmail.com", 993);
Ti.API.debug('Connect the socket');
socket.connect();
Ti.API.debug('Socket Connected');
var command = uniqueid()+" LOGIN USER PASS\r\n";
socket.write(command);
//this is where the debug stops. No echo.
Ti.API.debug('Command Run');
socket.onWrite(function(data) {
Ti.API.debug('Written to socket: '+data);
});
socket.onError(function(data) {
Ti.API.debug('Error: '+data);
});
socket.onReadComplete(function(data) {
Ti.API.debug('Here: '+data);
});
function uniqueid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 10; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23];
var uuid = s.join("");
return uuid;
}

Port 993 is for IMAP over SSL.

onWrite doesn't exist - thats a bug, and probably why your debug statements stop.
try moving your socket.connect() to after you define the handlers.
Use an interval, and socket.isClosed() before trying to write to the socket. Once you get a socket.isClosed() == false, then go ahead. Once you have the socket, you can play with it in the webinspector console in app as well.
This won't solve all your problems, but may help. You might want to try using a utility like wireshark to see what exactly you are sending down the wire when you socket.write, and compare that with what your email client sends.

Related

How to know if client is in sync with server in Meteor?

I am trying to implement a feature where I want the user to see if all requests to the server have been handled, i.e. that the client is in sync with the server so that the user can be confident that all his changes are saved.
My idea was to override Meteor.call and keep a counter for each call and then when a reply/error is returned I decrease the counter. I will then on the client show a message saying "Synced" if the counter is zero otherwise I will show "Unsynced".
Basically my question is if there is any "built-in" feature in Meteor which already handles this, keeping track of outgoing Meteor calls, or if I should proceed as I have started?
This is what my code looks at this moment:
var originalMeteorCall = Meteor.call;
var counter = 0;
Meteor.call = function() {
if (this.isClient) {
if (arguments && arguments.length > 1) {
counter++;
var returnFunc = arguments[arguments.length - 1];
var newReturnFunc = function (err, result) {
counter--;
return returnFunc(err, result);
}
arguments[arguments.length - 1] = newReturnFunc;
}
}
var result = originalMeteorCall.apply(this, arguments);
return result;
}

Game Maker Networking

Recently, I started playing around with Game Maker to make a very simple game with the ability to play online (multiplayer). I made a very simple client & server. I can send data from the server to the client, but I can't send the data from the client to the server.
Client: (Create event)
client_socket = network_create_socket(network_socket_tcp);
var server = network_connect(client_socket, "127.0.0.1", 5200);
if(server < 0) show_message("Could not connect! Try turning on the server?");
else{ //Send string
var t_buffer = buffer_create(256, buffer_grow, 1);
buffer_seek(t_buffer, buffer_seek_start, 0);
buffer_write(t_buffer , buffer_string, "Hello");
network_send_packet(client_socket, t_buffer, buffer_tell(t_buffer));
buffer_delete(t_buffer);
}
Server: (Create event)
server_socket = network_create_server(network_socket_tcp, 5200, 5);
(Async Network event)
var n_id = ds_map_find_value(async_load, "id");
if(n_id == server_socket){
var t = ds_map_find_value(async_load, "type");
socketlist = ds_list_create();
if(t == network_type_connect){
var sock = ds_map_find_value(async_load, "socket");
ds_list_add(socketlist, sock);
}
if(t == network_type_data){
var t_buffer = ds_map_find_value(async_load, "buffer");
var cmd_type = buffer_read(t_buffer, buffer_string);
show_message(cmd_type);
}
//show_message("Something happened!");
}
For some reason, the async network event in the server is never triggered when the client sends data. The message Something happened! only comes up when the client either connects or disconnects, but not when data is sent. Using almost the exact same code, I can send from the server, but not vice versa. Is this a problem with the code or just a server/client limitation?
This is the server side code:
var n_id = ds_map_find_value(async_load, "id");
if(n_id == server_socket){
var t = ds_map_find_value(async_load, "type");
socketlist = ds_list_create();
if(t == network_type_connect){
sock = ds_map_find_value(async_load, "socket");
ds_list_add(socketlist, sock);
}
}
if(n_id == sock) {
var t_buffer = ds_map_find_value(async_load, "buffer");
var cmd_type = buffer_read(t_buffer, buffer_string);
show_message(cmd_type);
}
You have to use the socket id when a message is arriving. The network_type_data will never be triggered.
Also, you have to declare the sock variable in the server's create event with a negative number (like noone (-4)).

SignalR disconnect function not recognized on client

public Task Disconnect()
{
var context = new HaiTaxiContainer();
var driver = context.OperatorEmployeeSet.Where(o => o.ConnectionId == Context.ConnectionId).FirstOrDefault();
driver.IsWorking = false;
driver.OperatorWorkingHistory.Add(new OperatorWorkingHistory
{
IsWorking = false,
Time = DateTime.Now
});
return Clients.leave(Context.ConnectionId, DateTime.Now.ToString()); ;
}
if (chat.disconnect!=null){
chat.disconnect(function () {
alert('Server has disconnected');
});
alert('Server disconnect==smt');
}else{
alert('Server disconnect==null');
}
The client chat.disconect is null. ANy ideeas why?
Based on your code it is hard to tell what you are actually doing - e.g., what is chat ? However, I think you should take a look at this related question / answer: https://stackoverflow.com/a/9122242/700926 about "How to determine server disconnection from SignalR client?" - it might be useful.

With node.js HTTP, how does res.end() guarantee a disconnection of the socket?

This is node.js' end implementation:
OutgoingMessage.prototype.end = function(data, encoding) {
if (this.finished) {
return false;
}
if (!this._header) {
this._implicitHeader();
}
if (data && !this._hasBody) {
console.error('This type of response MUST NOT have a body. ' +
'Ignoring data passed to end().');
data = false;
}
var ret;
var hot = this._headerSent === false &&
typeof(data) === 'string' &&
data.length > 0 &&
this.output.length === 0 &&
this.connection &&
this.connection.writable &&
this.connection._httpMessage === this;
if (hot) {
// Hot path. They're doing
// res.writeHead();
// res.end(blah);
// HACKY.
if (this.chunkedEncoding) {
var l = Buffer.byteLength(data, encoding).toString(16);
ret = this.connection.write(this._header + l + CRLF +
data + '\r\n0\r\n' +
this._trailer + '\r\n', encoding);
} else {
ret = this.connection.write(this._header + data, encoding);
}
this._headerSent = true;
} else if (data) {
// Normal body write.
ret = this.write(data, encoding);
}
if (!hot) {
if (this.chunkedEncoding) {
ret = this._send('0\r\n' + this._trailer + '\r\n'); // Last chunk.
} else {
// Force a flush, HACK.
ret = this._send('');
}
}
this.finished = true;
// There is the first message on the outgoing queue, and we've sent
// everything to the socket.
if (this.output.length === 0 && this.connection._httpMessage === this) {
debug('outgoing message end.');
this._finish();
}
return ret;
};
Source: https://github.com/joyent/node/blob/master/lib/http.js#L645
Apparently, the connection is only "finished" when output.length === 0.
So, if there is still data waiting to be written, and the receiving client for some reason is dodgy about receiving this data, will the request ever be ended?
I have also seen such issue where an end is not effective while trying to end a http request made by a flash uploader. I ended up doing the following, which did help:
res.end(failureJSON, 'utf8');
req.once('end', function _destroyConn() {
req.connection.destroy();
});
Seems very hackish. Anyway, is such behavior with req.connection.destroy needed to guarantee a disconnection from the socket?
Unfortunately, res.end() does not directly “guarantee a disconnection of the socket” because it needs to account for HTTP Keep-Alive. According to the docs, end tells the server that everything has been sent, and that the response is complete. It’s entirely up to the server object whether or not to disconnect immediately.
To answer your question more specifically, the important thing is that the response needs to emit a finish event. If you take a look at the implementation of _finish(), it pretty much just emits the event.
As you noted though, it doesn’t always call _finish() directly…but it did set this.finished = true. When _flush() executes, it sends any remaining data and THEN calls _finish().
It’s kind of complicated, and I don’t think I can go into any more detail without the risk of being wrong.
As far as connections sometimes not closing, have you checked if you have keep-alive configured properly? If the HTTP connection is set up with keep-alive by default, then calling end will not close the socket.
If your print out res.shouldKeepAlive, it will tell you if your server is trying to use keep-alive. Set it to false at the start of your request handler if you want to stop the server from doing this.
I don't know if this helps you as I am building my framework for node 4.4+ but I have confirmed that you can send Connection: close header in your response to get node to close the connection.
let res = getResponseSomehow()
res.statusCode = 408
res.setHeader("Connection", "close")
res.end()
Also your destroy code could use the following tweak:
// First we give node the time to close the connection
// We can give it 2 seconds
let socket = getSocketSomehow();
let timer = setTimeout(function() {
socket.destroy();
}, 2000);
socket.on("close", function() {
clearTimeout(timer);
});
I'm not quite sure if it's the close event you want. I normally try to use a library and stay away from the net api so this is just a guess.

AS3: Socket timeout

I get a vague "Socket timeout." error on occasion when I am loading my site. I make various HTTP requests for PHP data and also am using a Loader() class instance. Can anyone shed some light on where this error might be coming from?
I wish there was more of an indication of where the error stemmed from...
Here is my code that I am using.
There are multiple problems going on, but the most important is that catch{} catches an error on first load. I have a fade in function that only works if the loader is fully loaded and I know that all of my URL links work, so it can't be that.
public function loadImage(url:String):void
{
this._imageURL = url;
this.alpha = 1.0; //need this because we might have just faded the image out
_ldr.alpha = 0.0;
_prog.alpha = 1.0;
_sqr.alpha = 0.0;
try
{
_ldr.close();
_ldr.unload();
}
catch(e:Error)
{
trace("error in bmdisplay: " + e.message);
}
if(!_imageURL)
{
return;
}
_loaded = false;
_ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_ldr.load(new URLRequest(_imageURL));
}
Could you provide more precise information on what you're actually loading and how?
You should be able to get the exact request throwing the error by listening for the securityError and ioError events on the contentLoaderInfo of the Loader object.
Something like this:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorListener);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorListener);
var request:URLRequest = new URLRequest(url);
loader.load(request);
...
private function errorListener(event:Event):void {
var url_causing_the_error:String = LoaderInfo(event.target).loaderURL;
...
}

Resources