XMPPFramework Socket closed by remote peer - ios

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

Related

Objective-C Sockets Send and Receive on iOS

I'm very new to Objective-C and would like to communicate between an iOS app which I'm working on and my Python 3 socket server (which works). The problem is I don't know how to use sockets in Objective-C and don't know where to start when installing libraries in Xcode 8. For now I just want to be able to send data to the server and receive a response back on the iOS device. I have seen sys.socket.h but again, I don't know how to use it, any help would be much appreciated.
Thanks!
Few years ago I used SocketRocket. I am posting some of the code of it from my old project. I don't know if that still works but you might get the idea of using it.
Connecting to server
NSMutableURLRequest *pushServerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"ws://192.168.1.1"]];
[pushServerRequest setValue:#"WebSocket" forHTTPHeaderField:#"Upgrade"];
[pushServerRequest setValue:#"Upgrade" forHTTPHeaderField:#"Connection"];
[pushServerRequest setValue:"somekey" forHTTPHeaderField:#"Sec-WebSocket-Protocol"];
SRWebSocket *wsmain = [[SRWebSocket alloc] initWithURLRequest:pushServerRequest]; //Declare this as a global variable in a header file
wsmain.delegate=self;
[wsmain open];
Delegate Methods
-(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
NSLog(#"Message %#",message);
}
- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{ NSLog(#"Connected");
}
Sending Commands
[wsmain send:commands];
By sending commands, you will receive a response in didReceiveMessage method.
have you seen https://github.com/robbiehanson/CocoaAsyncSocket?
It's easy to use socket
NSString *host = #"10.70.0.22";
int port = 1212;
_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
NSError *error = nil;
[_socket connectToHost:host onPort:port error:&error];
if (error) {
NSLog(#"%#",error);
}
delegate
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
NSLog(#"success");
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
if (err) {
NSLog(#"error %#",err);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self connectToServer];
});
}else{
NSLog(#"disconnect");
}
}
Another option is socket.io. It has server libraries and a iOS client library written in Swift. It's API is quite extensive.

Socket closed by remote peer Error when server disconnected in 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");
}
}

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.

XMPP framework error: socket closed by remote peer

I am trying to connect to the ejabbered server with no SSL:
BOOL success;
if (![AppDelegate.xmppStream isConnected])
success = [AppDelegate.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error];
but, the server returns the error
socket closed by remote peer
In the:
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
I tried the following:
xmppPing = [XMPPPing new];
xmppPing.respondsToQueries = YES;
[xmppPing activate:xmppStream];
Also:
xmppAutoPing = [XMPPAutoPing new];
xmppAutoPing.pingInterval = 0.5;
[xmppAutoPing activate:xmppStream];
Also:
xmppStream.keepAliveInterval = 0.5;
But the error still exists. Is it something that I missed?
Log shows that connection accepted but returns the error:
(<0.455.0>:ejabberd_listener:281) : (#Port<0.2757>) Accepted
connection {{111,111,111,111},55012} -> {{222,222,222,222},5222}

iPad GCDAsyncSocket doesn't read

I really need some help with my project...
I need to exchange data with my server written in Java. I tried using GCDAsyncSocket, and I can send message to server, read it on server, but when server sends response to client, I can't (don't know how to) read it on client. Here is part of my code:
- (void) someMethod{
NSError *err = nil;
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
if(![asyncSocket connectToHost:#"localhost" onPort:7777 error:&err]){
// If there was an error, it's likely something like "already connected" or "no delegate set"
NSLog(#"I goofed: %#", err);
}
NSString *requestStr = #"<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><root><service>1</service><type>1</type><userProperties><username>ivo</username></userProperties></root>";
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:requestData withTimeout:-1.0 tag:0];
[asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:1.0 tag:0];
[asyncSocket disconnectAfterWriting];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
if (tag == 0)
NSLog(#"First request sent");
else if (tag == 2)
NSLog(#"Second request sent");
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
}
Please help, if there is another way I am willing to try as I am getting desperate...
I see that you're sending XML, with no particular terminator at the end of your request data, yet you're expecting the server to send a response terminated by a \r\n?
What does the protocol specify?
Sending and receiving data over tcp is a common cause of confusion because tcp is stream based. It has no concept of individual reads/writes. It treats all data as conceptually a never ending stream. The protocol dictates message boundaries. For a better explanation, see the "Common Pitfalls" article from GCDAsyncSocket's wiki:
https://github.com/robbiehanson/CocoaAsyncSocket/wiki/CommonPitfalls
I think it will help explain a lot.

Resources