Socket closed by remote peer Error when server disconnected in iOS - ios

I am using GCDAsyncSocket for connecting to socket. App works fine till phone gets lock.
When phone gets unlock then socketDidDisconnect gets call with error (Socket closed by remote peer). there I am reconnecting to server but socket gets disconnected every time. Is there any way to reconnect to socket?
Here is my Code :
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(#"Socket Disconnected===== %#",err);
[self serverConnection];
}
-(void)serverConnection
{
asyncSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![asyncSocket connectToHost:ipAddress onPort:portNumber error:&err]){
NSLog(#"Error in acceptOnPort:error: -> %#", err);
}
else
{
NSLog(#"Socket Connecting");
}
}

Related

Can you setup listener socket on localhost with iOS?

I'm trying to setup a listenerSocket on localhost using GCDAsyncSocket for iOS device.
In the socketDidDisconnect delegate I either get error Code=49 for trying with port 0 (which I'm hoping would find the first available free port).
Or if I use a port no then I get error Code=61 for trying to connect with localhost.
- (IBAction)start:(id)sender {
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if(![asyncSocket connectToHost:#"localhost" onPort:0 error:&err])
{
NSLog(#"Connect Error: %#", err);
}
}
#pragma mark – delegate
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(#"socketDidDisconnect");
if (err) {
NSLog(#"Socket Error: %#", err);
// Error in connect function:
// NSPOSIXErrorDomain Code=49 "Can't assign requested address" - onPort:0
// NSPOSIXErrorDomain Code=61 "Connection refused" - connectToHost:#"localhost"
}
}
connectToHost will act as the client-side of the connection. You want to read the Writing a server section of the help page:
listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![listenSocket acceptOnPort:port error:&error])
{
NSLog(#"I goofed: %#", error);
}
- (void)socket:(GCDAsyncSocket *)sender didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
// The "sender" parameter is the listenSocket we created.
// The "newSocket" is a new instance of GCDAsyncSocket.
// It represents the accepted incoming client connection.
// Do server stuff with newSocket...
}
However you need to know the port to use (if you let the system decide what port to use then how is a client supposed to know how to connect to the server?). Also the port will almost certainly need to be > 1024 (out of the reserved port range). However I haven't ever tried to create a Server on iOS.

XMPPFramework Socket closed by remote peer

I'm trying to implement the XMPPFramework by robbiehanson. The problem is, that I get the following error message:
Error Domain=GCDAsyncSocketErrorDomain Code=7 "Socket closed by remote peer" UserInfo=0x9517440 {NSLocalizedDescription=Socket closed by remote peer}
I already tried everything I could find on the internet (XMPPPing etc.) but nothing could fix my problem. Here is the code I'm using:
- (void)connect {
stream = [[XMPPStream alloc] init];
[stream setEnableBackgroundingSocket:YES];
[stream addDelegate:self delegateQueue:dispatch_get_main_queue()];
reconnect = [[XMPPReconnect alloc] init];
[reconnect activate:stream];
[stream setHostName:_hostName];
[stream setPort:5223];
[stream setMyJID:[XMPPJID jidWithString:_username];
NSError *e;
if(![stream connectWithTimeout:20 error:&e]) {
NSLog(#"%#", e);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender {
NSError *e;
[sender authenticateWithPassword:_password];
if(e) {
NSLog(#"%#", e);
}
}
I'm getting this error message immediately, not after several seconds. I already thought it might be, because our server requires SSL, but the only solution I found for SSL was running [stream secureConnection:nil]; and this only works if connected.
I also never get the -xmppStreamDidConnect: delegate method.
stream oldSchoolSecureConnectWithTimeout: will connect to 5223/SSL

why GCDAsyncUdpSocket cannot send/receive packets after a while in broadcast mode?

I am using GCDAsyncUdpSocket to write a UDP socket in my app. The scenario is like this: when users click the button, it will send a broadcast packet in LAN then listen to the response, there is a server in LAN which will respond with one UDP packet. When the app receives the response, it will do something.
I set GCDAsyncUdpSocket as followings:
- (void)setupSocket
{
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![_udpSocket bindToPort:18686 error:&error]) {
NSLog(#"Error binding: %#",error);
return;
}
if (![_udpSocket beginReceiving:&error]) {
NSLog(#"Error receiving: %#",error);
return;
}
if (![_udpSocket enableBroadcast:YES error:&error]) {
NSLog(#"Error enableBroadcast: %#",error);
return;
}
}
then i send Packet in button action as following:
NSString *host = #"255.255.255.255";
int port = 8585;
NSString *msg = #"Hello from iOS";
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[_udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];
in
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
method i listen the port to do somethings. It works perfectly at beginning, but if you try to click the button later (about 1 hour), then it cannot send UDP packet any more.
My server in LAN will print the data received. I thought there was something wrong with send method. so i use BSD socket methods to send The data. and use GCDAsyncUdpSocket to receive the response. but the same thing happened after a while. this time i can send but cannot receive.
Am i missing something about GCDAsyncUdpSocket? why it cannot send/receive after a while? Any help would be much appreciated.
It may be some timeout setting. Implement the GCDAsyncUdpSocketDelegate protocol to fetch detailed information about what is going on.
The hard solution is to establish a new connection.

Node JS udp broadcast not read -- node js and iOS

here is my code (javascript for node):
var dgram = require('dgram');
var message = new Buffer("why hello beautiful");
var client = dgram.createSocket("udp4");
client.bind(41234);
client.setBroadcast(true);
client.send(message, 0, message.length, 41234, "134.71.147.255");
console.log('msg sent');
client.close();
here is the ifconfig for my computer running node (the only pertinent thing I think -- correct me if im wrong please):
inet addr:134.71.146.49 Bcast:134.71.147.255 Mask:255.255.254.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
The udp broacast is neither recieved on my iOS app nor visible through a packet inspector.
What is going wrong?! The iOS app uses the GCDAsyncUdpSocket framework:
- (void) initUDPlistener {
NSLog(#"initUDPlistener");
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![udpSocket bindToPort:UDP_PORT error:&error]) //does the port matter? i dont know
{
return;
}
if (![udpSocket beginReceiving:&error])
{
return;
}
[udpSocket enableBroadcast:YES error:nil];
[udpSocket sendData:[self pack:#"iOS to bcast"] toHost:UDP_BCAST_ADDR port:UDP_PORT withTimeout:-1 tag:0];
}
#pragma mark -
#pragma mark Delegate UDP methods
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
NSLog(#"niets.");
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
NSLog(#"iets gekregen");
}
else
{
NSLog(#"Error convertion");
}
NSLog(#"HMMMM");
}
-(void) udpSocket:(GCDAsyncUdpSocket *) sock didSendDataWithTag:(long)tag {//called. and packet inspector recieves the packet when it is sent OUT from the iOS app.
NSLog(#"written data tag: %ld", tag);
}
-(void) udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address { //never called
NSLog(#"connected to some address");
}
What happens:
"didReceiveData" does not get called from the node broadcast. It gets called when it sends its own message out, however.
the iOS app, on the other hand, successfully broadcasts and i am able to intercept that packet on my packet inspector. The same packet inspector does not show packets that should be originating from Node, however.
what am I doing wrong in node? I think what I am doing in node is the problem.

Socket Disconnect call during iOS Suspend doesn't disconnect socket

I am using GCDAsyncSocket in my application. I have a few problems.
When the app goes to background, I like to close the socket. During Suspend applicationDidEnterBackground call, I execute the following code but it doesn't disconnect the socket. (I check this via connected host)
[asyncSocket setDelegate:nil];
[asyncSocket disconnect];
[asyncSocket setDelegate:self];
Once I standby the phone, despite my call, the socket is not closed. After 60 seconds iOS closes the socket since we are at background and things go back to normal but the sender lost 60 seconds of data. I am probably not using API correctly but it could also be an issue.
Rest of my code below for reference:
Initialization
dispatch_queue_t socketQ = dispatch_queue_create("socketQueue", NULL);
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQ];
if(![asyncSocket connectedPort])
{
if (![asyncSocket acceptOnPort:WIFI_BOX_PORT error:&error])
{
NSLog(#"Problem with opening Port: %#", error);
}
else
{
NSLog(#"Port opened, waiting for connection");
}
}

Resources