Giter VIP home page Giter VIP logo

cocoaasyncsocket's Introduction

CocoaAsyncSocket

Build Status Version Status Carthage compatible Platform license Public Domain

CocoaAsyncSocket provides easy-to-use and powerful asynchronous socket libraries for macOS, iOS, and tvOS. The classes are described below.

Installation

CocoaPods

Install using CocoaPods by adding this line to your Podfile:

use_frameworks! # Add this if you are targeting iOS 8+ or using Swift
pod 'CocoaAsyncSocket'  

Carthage

CocoaAsyncSocket is Carthage compatible. To include it add the following line to your Cartfile

github "robbiehanson/CocoaAsyncSocket" "master"

The project is currently configured to build for iOS, tvOS and Mac. After building with carthage the resultant frameworks will be stored in:

  • Carthage/Build/iOS/CocoaAsyncSocket.framework
  • Carthage/Build/tvOS/CocoaAsyncSocket.framework
  • Carthage/Build/Mac/CocoaAsyncSocket.framework

Select the correct framework(s) and drag it into your project.

Swift Package Manager

Simply add the package dependency to your Package.swift and depend on "CocoaAsyncSocket" in the necessary targets:

dependencies: [
    .package(url: "https://github.com/robbiehanson/CocoaAsyncSocket", from: "7.6.4")
]

Manual

You can also include it into your project by adding the source files directly, but you should probably be using a dependency manager to keep up to date.

Importing

Using Objective-C:

// When using Clang Modules:
@import CocoaAsyncSocket; 

// or when not:
#import "GCDAsyncSocket.h" // for TCP
#import "GCDAsyncUdpSocket.h" // for UDP

Using Swift:

import CocoaAsyncSocket

TCP

GCDAsyncSocket is a TCP/IP socket networking library built atop Grand Central Dispatch. Here are the key features available:

  • Native Objective-C, fully self-contained in one class.
    No need to muck around with sockets or streams. This class handles everything for you.

  • Full delegate support
    Errors, connections, read completions, write completions, progress, and disconnections all result in a call to your delegate method.

  • Queued non-blocking reads and writes, with optional timeouts.
    You tell it what to read or write, and it handles everything for you. Queueing, buffering, and searching for termination sequences within the stream - all handled for you automatically.

  • Automatic socket acceptance.
    Spin up a server socket, tell it to accept connections, and it will call you with new instances of itself for each connection.

  • Support for TCP streams over IPv4 and IPv6.
    Automatically connect to IPv4 or IPv6 hosts. Automatically accept incoming connections over both IPv4 and IPv6 with a single instance of this class. No more worrying about multiple sockets.

  • Support for TLS / SSL
    Secure your socket with ease using just a single method call. Available for both client and server sockets.

  • Fully GCD based and Thread-Safe
    It runs entirely within its own GCD dispatch_queue, and is completely thread-safe. Further, the delegate methods are all invoked asynchronously onto a dispatch_queue of your choosing. This means parallel operation of your socket code, and your delegate/processing code.

UDP

GCDAsyncUdpSocket is a UDP/IP socket networking library built atop Grand Central Dispatch. Here are the key features available:

  • Native Objective-C, fully self-contained in one class.
    No need to muck around with low-level sockets. This class handles everything for you.

  • Full delegate support.
    Errors, send completions, receive completions, and disconnections all result in a call to your delegate method.

  • Queued non-blocking send and receive operations, with optional timeouts.
    You tell it what to send or receive, and it handles everything for you. Queueing, buffering, waiting and checking errno - all handled for you automatically.

  • Support for IPv4 and IPv6.
    Automatically send/recv using IPv4 and/or IPv6. No more worrying about multiple sockets.

  • Fully GCD based and Thread-Safe
    It runs entirely within its own GCD dispatch_queue, and is completely thread-safe. Further, the delegate methods are all invoked asynchronously onto a dispatch_queue of your choosing. This means parallel operation of your socket code, and your delegate/processing code.


For those new(ish) to networking, it's recommended you read the wiki.
Sockets might not work exactly like you think they do...

Still got questions? Try the CocoaAsyncSocket Mailing List.


Love the project? Wanna buy me a ☕️  ? (or a 🍺  😀 ):

donation-bitcoin donation-paypal

cocoaasyncsocket's People

Contributors

boraseoksoon avatar chaoscoder avatar chrisballinger avatar cyrusingraham avatar darkfader avatar dede avatar dsmurfin avatar dvor avatar epatey avatar erichocean avatar esad avatar jdewind avatar jdiehl avatar jeeftor avatar johannesrudolph avatar maddthesane avatar mattsoftware avatar mittsh avatar mrvincenzo avatar nifly avatar noskthing avatar pablometermax avatar pcbeard avatar pizthewiz avatar qmfrederik avatar robbiehanson avatar rocklobster avatar rpendleton avatar rrrus avatar seanm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cocoaasyncsocket's Issues

CFSocketSetAddress in AsyncUDPSocket fails with broadcast address

What steps will reproduce the problem?

  1. hostname is set to 192.168.137.255, port 1002
  2. enableBroadcast is set to yes

[remoteSocket bindToAddress:hostname port:thePort error:&err]
fails with the error
Cannot accept connections on port 1002. Error domain AsyncUdpSocketErrorDomain code -1 (General CFSocket error).

Interestingly, I believe the problem is with multiple physical ethernet interfaces. 192.168.137.255 is a net on en1 not en0. It appears that the same code works fine when the broadcast hostname *.255 is routed to en0, but not to en1.

What is the expected output? What do you see instead?
Expect success. Instead:
Cannot accept connections on port 1002. Error domain AsyncUdpSocketErrorDomain code -1 (General CFSocket error).

What version of the product are you using? On what operating system?
Dec 11 version, 10.6.8

Please provide any additional information below.

Doesn't seem to be a permissions issue. Fails under sudo as well.

ARC under Mountain Lion

Hello,

Adding -fobjc-arc works fine under Lion but it doesn't under Mountain Lion.

It really doesn't like the dispatch_release calls at all.

Just wanted to let you know that.

Missing framework and GCD error

Hello,

I'm trying to use GCDAsyncSocket.m in a new projet, but no way of doing that without :

  • Adding CFNetwork.framework (solve 6 compiler issue) (so it need a configuration after all)

Even then, I've got error like : Undefined symbols for architecture i386:
"_SSLClose", referenced from:
-[GCDAsyncSocket closeWithError:] in GCDAsyncSocket.o
(trying to run it on the iphone 5.1 simulator)

GCDAsyncUdpSocket.m seem to suffer from errors related to Arc, mainly bridge casting, and some function that are not compatible by arc.

I'll gladly help, but can't for now — arc error are a mystery for me now.

Tested on Xcode 4.3.2.

Is there a way to get partial data read and clear the buffer?

Hi ! I'm working on a project that the client will send only TCP partial data so every time the data is received, the didReadPartialData is called but never the didReadData. Actually the client is sending stream without indicating the end of data. Is there a way to deal with this?

Thanks in advance!

Using readDataToData and readDataToLength together seems to cause problems

I haven't really tested this but i really think there's an issue here. In my application i use readDataToLength on my messages that have a static length (like just a packaged 16bit-int or somethign) and readDataToData on other (strings). The first byte of every message tells the program to either read to a certain length or to a separator.

So let's say i know that the first message is a encoded string. I tell the program to read to CRLF. No problems this far. Now, as I mentioned every message is preceded by a byte (char) that says how i should terminate the incoming message. So I have to read the next byte to know what to do next. I do so:

[sock readDataToLength:1 withTimeout:-1 tag:0]

And here's the problem. The first byte after reading to CRLF is not what i expected it to be, its actually the CRLFdata itself.

I'm not really into how the whole class works but i would guess there's some sort array holding all the received bytes and when u call readDataToData it just goes through that array until it finds ur separator and then returns everything before (but more complicated possibly). And the problem being that it does not remove the separator from this "buffer", only when u call readDataToData again. So thats why this problem is only visible when you first do a readDataToData followed by a readDataToLength.

So as I said, I'm not sure about this, but it seems to make sense to me that this could occur.

Edit: This is about GCDAsyncSocket but might apply to AsyncSocket aswell

Different behaviours in iOS simulator and device (iOS5)

I' trying to user AsyncUdpSocket class to make a ssdp discovery run on my program.

I implemented everything to send and read from port 1900, address 239.255.255.250.

In the simulator, everything is 100%. The exact same code, in a device, does not receive a thing. The device sends the package and I see the packets of the response in the network with wireshark but the device just ignores them.

Is there some sort of knonw issue with iOS5 or similar?

the code i use is as follows:

AsyncUdpSocket *ssdpSocket = [[AsyncUdpSocket alloc] initIPv4];
[ssdpSocket setDelegate:self];

[ssdpSocket enableBroadcast:YES error:nil];

[ssdpSocket bindToPort:1900 error:nil];

[ssdpSocket joinMulticastGroup:@"239.255.255.250" error:&error];

[ssdpSocket receiveWithTimeout:-1 tag:1];

[ssdpSocket sendData:[self somedata] toHost:@"239.255.255.250" port:1900 withTimeout:-1 tag:1];

void

Never mind, I deleted the original issue description, it was my fault.

AsyncUdpSocket Broken pipe signal crash on screen lock

Hi,
This is a copy of the issue from the previous SVN space:
http://code.google.com/p/cocoaasyncsocket/issues/detail?id=103&colspec=ID%20Type%20Status%20Priority%20Component%20Summary

I'm still experiencing this and was wondering if someone had already investigated this subject.

Update:
Seems to be an issue with iOS 5 shutting down network connections when going to screen lock.
I worked around it for now by:

  1. signal( SIGPIPE, SIG_IGN ) [right now only in the caller, not the lib]
  2. cleanup and create a new AsyncUdpSocket on send error with Broken pipe

Thanks.

Use of wildcards in readDataToData?

I was wondering if this is something that can be done? Often I have a response where I don't control the protocol, and it is so weakly formatted that I need to identify the ending data by the beginning and the ending of the line. Given well-formatted protocols this isn't necessary, but all I have to go on is something like the following in my response (where * is the wildcard):

"Message: *\r\n"

Many thanks. :)

Reinitialize connection after device removal

In my setup I'm using GCDAsyncSocket (ARC branche) to communicate with a printer behind an Airport Express. This works fine and I've got it working pretty well.

However it is unable to recover the connection when I pull out the Airport Express and put it back in. When I plug the Airport Express back in it will restore the connection, but the first read I do will simply timeout (so it isn't a proper connection).

The only solution is to restart the iOS Simulator.

Is there some way to force the release of a socket? Or force it to timeout?

Error when receive multiple data at a time

I`m using GCDAsyncUDPSocket.

Because of some reason, I send a message and server get it.
Server check it and answer.

There is two type of answer. First is just transfer data once. Second is transfer 20 times.

When receive a data, It works well. The problem is second type.

It randomly stops with error.

Thread x : Program received signal: "SIGABRT"
malloc : *** error for object 0x?????? : pointer being freed was not allocated

Error occurs almost in [-(void) notifyDidCloseWithError:(NSError *) error] but some other method also.
(I dont know well because I didnt captured all of error)
And occurs in Thread 2 (dont think its so important but no clear.... :( )

At the first time, I thought there is some problem with allocated resources. So I tried UDP communication with just using your library, don`t allocate other resource. But same error occured.

My project using ARC option but I added option [-fno-objc-arc] on your source.

Oh... I have searched about this problem... Please help ;(

Not Receiving Response - UDP

Hello,

I am wondering if you could help;

I am trying to get a response from my UDP server, I know it is sending one, but I can't for the life of me get the application to notice it.

My project is very small at the moment, and is currently just in the AppDelegate, which i have pastebin'd incase you wouldn't mind taking a look.

http://pastebin.com/mUvsqD4B

Here is the tcpdump:

03:13:52.876484 IP 192.168.2.36.60524 > ipadrs.28960: UDP, length 25
03:13:52.969327 IP ipadrs.28960 > 192.168.2.36.60524: UDP, length 240

ipadrs being the servers ip.

I would love any kind of advice, cheers.

Oliver

It's not possible for me to use it for broadcast

Hi Robbie!!
Updated: My speciefic task, i don't know my custom device IP, so i need to send both broadast and normal request to one port, so i can't open 2 of them as i understand, how to deal with it?

I've tried to make 2 sockets - 1 for broadcast and other for communication but it also fails, i don't know why but broadcast works only when i initialize it once with this code, then I'm closing socket and only after another initialization it works. How to deal with this? How to send broadcast? Do i need to use 2 sockets or 1? Thank u very much, i can't do this for 3 days ...
Everything else works perfectly i can send and receive with no problem.

udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

NSError *error = nil;

[udpSocket setIPv4Enabled:YES];
[udpSocket setIPv6Enabled:NO];
  [udpSocket enableBroadcast:YES error:&error];

   if (![udpSocket  bindToPort:30303 error:&error])  { NSLog(@"Error starting server (bind): %@", error); return;    }

if (![udpSocket beginReceiving:&error])
{ [udpSocket close];
    NSLog(@"Error starting server (recv): %@", error);  return;
}

NSLog(@"Udp Echo server started on port %hu", [udpSocket localPort]);
isRunning = YES;
// --------------------

NSData* datatosend=[UDPString dataUsingEncoding:NSUTF8StringEncoding];
NSString* mysubnet= [[NSString alloc] initWithFormat: @"%i.%i.%i.255", myip1,myip2,myip3];

[udpSocket sendData:datatosend toHost:mysubnet port:port withTimeout:-1 tag:0];

Bug/Crash: AsyncSocket missing a retain call

I ran into a crash when trying the EchoServer sample:

In AsyncSocket.m, "- (id)initWithDelegate:(id)delegate userData:(long)userData", there's this line:

theRunLoopModes = [NSArray arrayWithObject:NSDefaultRunLoopMode];

it needs to be:

theRunLoopModes = [[NSArray arrayWithObject:NSDefaultRunLoopMode] retain];

Tags don't match in callback

If I make two concurrent read requests the tag that gets sent to onSocket:didReadData:withTag: often doesnt match the tag used in readDataWithTimeout:tag: (they get switched around and the response from one, gets tagged with the others tag)

GCDAsyncUdpSocket ARC errors

Hi,

It looks like the GCDAsyncUdpSocket is not yet fully ready to use with ARC, as I get some errors such as "ARC forbids explicit message send of 'retain'" .

Am I right?

Connecting to an invalid host does not fail

I use GCDAsyncSocket to connect to an own TCP server of mine. I noticed that the socket never fails nor gives any error when the hostname is invalid and does not exist:

self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

host = @"totallyinvalid";

NSError * error = nil;
if ( ! [self.socket connectToHost:host onPort:29927 withTimeout:10 error:&error] ) {
    NSLog( @"failed to connect" );
    return;
}
if ( error ) {
    NSLog( @"failed to connect: %@", [error localizedDescription] );
    return;
}

Nor are the timeout callbacks called, even when running for a long time. Any way to work around this? The hostnames I've tried with do not resolve to anything at all and even when trying with an invalid IP there is no error.

Tags

Project should have tags added for various versions, etc.

Not able to do SSL + Proxy connection together??

I need to first connect to my office network proxy using the "connectoToHost:" and then send it the "CONNECT " HTTP handshake message which will return "CONNECTION ESTABLISHED" after which I need to convert it to a SSL socket using "startTLS" method to connect to the desired IP mentioned in the CONNECT message.

  1. Connect to proxy using "connecttohost: onPort" method specifying the proxy ip and port.
  2. send "CONNECT" message as " connect : ..."
  3. Once "CONNECTION ESTABLISHED", I need to convert the socket to ssl to conenct to another IP mentioned in CONNECT message through the SSL socket

Please help!! Very urgent.

Unable to compile

after successfull cloning of xmpp framework I have downloaded the local xmpp sample project from the repository and tried to compile it but I'm getting the errors I tried to compile the xmpp iphone example project and I'm getting the Parse issue error on here

@Property (strong, readonly) NSString *user;
@Property (strong, readonly) NSString *domain;
@Property (strong, readonly) NSString *resource;

and also an unexpected '@' here

@autoreleasepool {
int retVal = UIApplicationMain(argc, argv, nil, nil);
return retVal;

Can you please help me out as I'm working on the important project. Thank you.

Starting AsyncSocket in another class (Not in the App Delegate)

Hey, Robbie!

I'm searching it and I don't found in any place in the web: I'm trying to start a TCP Socket not from the initial class (AppDelegate), but from another one that I created, as netClass (That have a void - start - that uses the SAME CODE that applicationDidFinishLaunching[...]), and I call this method (netClass->start that starts the connection - socket) from my applicationDidFinishLaunching method, in my AppDelegate. It's running normally, but incredibly, it don't call the delegate methods, as "didConnectToHost", and "didAcceptNewSocket".

Take a look in my question in Stack Overflow: http://stackoverflow.com/questions/10676780/global-socket-starts-asyncsocket;

Is there any way to start it from another class, or I just have the option to start it from App Delegate? I'm questioning here because I don't know what do more.

Thanks a lot for the help.

Bind error on port 69 on ios4 , working on ios 5

Steps to reproduce : run on ios4 IPAD
CODE:
socket = [[AsyncUdpSocket alloc] initWithDelegate:self];
if (![socket bindToPort:69 error:&error]){
NSLog(@"Bind error %@",[error description]);
}

reboot ipad to ensure no application is running on 69
Exception occured: Bind error on 69Error Domain=AsynchUdpErrorDomain Code =-1 "General CFSocket error" ....

but strange behavior was : socket on 69 was working properly.

tried on ios 5 no such exception coming.

file descriptor leak

GCDAsyncSocket.m there seems to be a leak if there is a failure to connect. I noticed there was an update that closes the file descriptors in closeWithError, but I don't know if they cover the same path.

  • (void)didNotConnect:(int)aConnectIndex error:(NSError *)error
    {
    LogTrace();

    NSAssert(dispatch_get_current_queue() == socketQueue, @"Must be dispatched on socketQueue");

    if (aConnectIndex != connectIndex)
    {
    LogInfo(@"Ignoring didNotConnect, already disconnected");

    // The connect operation has been cancelled.
    // That is, socket was disconnected, or connection has already timed out.
    return;
    

    }

    [self endConnectTimeout];

    // There seems to be a bug here if you fail to connect, the connectInterface4 and 6 objects
    // are not set up so they do not get cleared by the cancel routine or the endConnectTimeout
    // routine. Close the socket here since "close with error" presumes that it was already closed
    // by the time it was canceled.
    if(socket4FD != SOCKET_NULL) {
    close(socket4FD);
    }

    if(socket6FD != SOCKET_NULL) {
    close(socket6FD);
    }

    [self closeWithError:error];
    }

Read & Write timeout issue

Hi Robbie,

I found a strange thing, when I use GCDAsyncSocket connected to a server, they can communication well, after I closed the server, GCDAsyncSocket will receive the disconnect message, after that, if I still read or send data with server, timeout will not work, in other words, I could not receive the timeout error, looking forward yo your replay, thanks.

Is AsyncSocket suitable for subscription events?

Currently, I'm trying to use AsyncSocket and I see its not suitable for handling subscription type events (reading data that came from a server without request (write)). The "response packets" do not have terminator chars, just length defined in the first bytes of packet. I was unable to find related info on its wiki. Everything is OK when every write you make (request) is paired with a read (a server sends a response). AsyncSocket manages it via its tags. But in my case, I also have subscription functionality where I'm writing to server one request like "start getting location updates from a server" and then I'm receiving multiple responses (reads), so they are not paired with writes.

First, I'v added a callback in AsyncSocket doBytesAvailable that notified my delegate object when such read occurs:

- (void)doBytesAvailable {
  // If data is available on the stream, but there is no read request, then we don't need to process the data yet.

  // Also, if there is a read request but no read stream setup, we can't process any data yet.

  if (theReadStream == NULL)

    return;

  if (theCurrentRead == nil) {  

    // My fix: Notify about received data for missing read:
    [theDelegate didReceiveEventsFromSubscription];
    return;
  }

But the length of "response" packets is variable, so I need to grab existing read data, extract "response" length, make callback to my delegate with that data and then call readToLength on socket. I'm not very comfortable with making code modifications to AsyncSocket internal code. Just curious are there any options or am I missing smith?

How to define custom rule for splitting read streams into packets

I rewrote the question to be more precise on the solution I'm looking for:

Is it possible to do the following with AsyncSocket:

while ("response packet" is not read) do {

  1. Read at least first 5 bytes from read stream, and extract "response packet" length size from that.
  2. Read further until reached reading amount of bytes defined in "response packet" header.
  3. If reached the end of read stream but some bytes are lacking then wait for another read stream and finish reading the "response packet" then.
  4. Copy read bytes into buffer and mark that read data as "response packet" data.
  5. Do callback to my delegate onSocket:didReadData:withTag: with that data.
  6. clear buffer (response packet) and do the same steps with the next read streams.

}

Here's my current usage of AsyncSocket:

I'm writing a data via socket with AsyncSocket:

[_socket writeData:request withTimeout:commandData tag:commandTag];

and receiving a callback in my delegate class:

onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

The problem is, there's no terminating char in data stream and the only way to distinguish the length of comming "response packets" is to read and parse their first 5 bytes and use that for cutting data into "packets" and making callbacks to my delegate. Currently, I'm using AsyncSocket as shown in code fragment above, and some callbacks "onSocket:didReadData:withTag:" are already good length data packets (received NSData), but some are merged. IMHO I need explicitly to tell AsyncSocket how to interpret and cut coming data into packets when reading.

Original post you can find here: http://stackoverflow.com/questions/9359391/asyncsocket-getting-merged-two-packets-instead-of-separate-two-packets

Library missing? Undefined symbols for architecture i386:. "_OBJC_CLASS_$_GCDAsyncSocket"...

I started a new project using GCDAsyncSocket and added the iOS 5.1 Security Framework to the project libraries.
However, when compiling the project, I get the error message: "Undefined symbols for architecture i386:. "OBJC_CLASS$_GCDAsyncSocket", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture i386 and clang: error: linker command failed with exit code 1".

What am I missing?

I would appreciate any help!

How to compatible with ios4.3?

Hi,

The code works well when i set Deployment Target to iOS5.0,but when i set Deployment Target to iOS4.3 when
[asyncSocket setDelegate:nil];
[asyncSocket disconnect];
[asyncSocket release];
called it crash in function "- (void)completeCurrentRead "
in line 2738:[theDelegate socketDidDisconnect:self withError:error];

Is the class only work on iOS5.0 or later?

thanks.

Best regards
Sam

Not working in non-ARC project.

The instructions mentioned at https://github.com/robbiehanson/CocoaAsyncSocket/wiki/ARC no longer seem to work in non-arc projects under Xcode 4.3.2. Normally I wouldn't care too much about this, but I am developing a System Preference Pane and would like to use AsyncSocket with it -- and it appears that System Preference Panes are non-arc only.

This is the message I get in a fresh Preference Pane project with no code, and only making the alterations as recommended per the above link:

ProcessPCH /Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/PrecompiledHeaders/Clixterisk-Prefix-dfweqlcnonpupzfuqablxrhgmvkn/Clixterisk-Prefix.pch.pth Clixterisk/Clixterisk-Prefix.pch normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
cd /Users/mikebronner/Developer/Clixterisk
setenv LANG en_US.US-ASCII
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c-header -arch x86_64 -fmessage-length=0 -std=gnu99 -fobjc-gc -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Wreturn-type -Wno-implicit-atomic-properties -Wformat -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-sign-compare -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -DDEBUG=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk -fasm-blocks -Wprotocol -Wdeprecated-declarations -mmacosx-version-min=10.7 -g -Wno-conversion -Wno-sign-conversion "-DIBOutlet=attribute((iboutlet))" "-DIBOutletCollection(ClassName)=attribute((iboutletcollection(ClassName)))" "-DIBAction=void)attribute((ibaction)" -iquote /Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/Clixterisk.build/Debug/Clixterisk.build/Clixterisk-generated-files.hmap -I/Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/Clixterisk.build/Debug/Clixterisk.build/Clixterisk-own-target-headers.hmap -I/Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/Clixterisk.build/Debug/Clixterisk.build/Clixterisk-all-target-headers.hmap -iquote /Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/Clixterisk.build/Debug/Clixterisk.build/Clixterisk-project-headers.hmap -I/Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Products/Debug/include -I/Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/Clixterisk.build/Debug/Clixterisk.build/DerivedSources/x86_64 -I/Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/Clixterisk.build/Debug/Clixterisk.build/DerivedSources -F/Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Products/Debug -fobjc-arc --serialize-diagnostics /Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/PrecompiledHeaders/Clixterisk-Prefix-dfweqlcnonpupzfuqablxrhgmvkn/Clixterisk-Prefix.pch.dia -c /Users/mikebronner/Developer/Clixterisk/Clixterisk/Clixterisk-Prefix.pch -o /Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/PrecompiledHeaders/Clixterisk-Prefix-dfweqlcnonpupzfuqablxrhgmvkn/Clixterisk-Prefix.pch.pth -MMD -MT dependencies -MF /Users/mikebronner/Library/Developer/Xcode/DerivedData/Clixterisk-gcjcwicssgmjoucwirtkytsawidu/Build/Intermediates/PrecompiledHeaders/Clixterisk-Prefix-dfweqlcnonpupzfuqablxrhgmvkn/Clixterisk-Prefix.pch.d

clang: error: cannot specify both '-fobjc-arc' and '-fobjc-gc'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

cocoapod on osx needs security framework

Hi,

Just letting you know that in order to get the cocoapod working in an OSX app i had to also add the 'security' framework to my app. It might be obvious to you (and some other people) but for an objc noob like me it was quite a confusing and time consuming exercise getting everything to work, as a result you may want to mention something about this in your readme,

cheers for the great library!

Is CocoaAsyncSocket ported to iOS5 (ARC)?

Hi,

I've tested CocoaAsyncSocket on a iOS4 project and worked well so far.

But then I wanted to use it in a ARC project, and of course it complained.
I've tried to remove all the release/retains/autorelease/dealloc/etc calls and after that I've let xcode port it to arc, it seemed with success.
But then it crashes badly on doSend when passing the msg, which is NSData as it should be I think.

At the line:
const void *buffer = [currentSend->buffer bytes];
in GCDAsyncUdpSocket.m (in doSend)
it seems "buffer" is empty.

Any chances to help me shed some light on this (I'm not a objective-super-guru :/ )

Is there a port to ARC somewhere?

Thanks!
Luca

setting SO_REUSEPORT as well as SO_REUSEADDR

in AsyncUDPSocket.m - (BOOL)bindToAddress:(NSString )host port:(UInt16)port error:(NSError *)errPtr

SO_REUSEADDR is set, should it also set SO_REUSEPORT at least optionally?

Check to non default Root Certificate

I'd like to use CACert or a custom Root Cert to secure my connections.
I haven't found a way to do it directly do this, so I do it afterwards. This is how it looks like.
Is there a better way of doing this?/Could this (functionality) be implemented directly into GCDAsyncSocket?

kCFStreamSSLAllowsAnyRoot is set to true

- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
    [sock performBlock:^{
        CFReadStreamRef readStream=[sock readStream];

        // Create SecTrustRef from Stream
        CFTypeRef ref=CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates);
        SecPolicyRef policy = SecPolicyCreateSSL(NO, (__bridge CFStringRef)[sock theHost]);
        SecTrustRef trust = NULL;
        SecTrustCreateWithCertificates(ref, policy, &trust);

        // Get our Root
        NSString *path=[[NSBundle mainBundle] pathForResource:@"CACert-class3" ofType:@"der"];
        NSData *certData=[NSData dataWithContentsOfFile:path];
        SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);

        // Verify
        SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)[NSArray arrayWithObject:(__bridge id)cert]);
        SecTrustResultType trustResultType = kSecTrustResultInvalid;
        OSStatus status = SecTrustEvaluate(trust, &trustResultType);

        if (status == errSecSuccess) {
            if (trustResultType == kSecTrustResultUnspecified) {
                NSLog(@"%@ is Trustworthy", [sock theHost]);
            } else {
                NSLog(@"%@ is EVIL ;)", [sock theHost]);
            }
        } else {
            NSLog(@"SecTrustEvaluate failed");
        }
    }];
}

Why SimpleHTTPClient can't receive the Http body?

I want to use CocoaAsyncSocket to get some html from the server. There is a demo under GCD directory:SimpleHTTPClient,

I change a little as below:
[asyncSocket readDataWithTimeout:10 tag:1];
//[asyncSocket readDataToData:responseTerminatorData withTimeout:-1.0 tag:0];

But only receive the Http response header, can't receive the Http body, I use the BSD Socket directly, and can get the response header and body successfully.

Hope give me Tech. support.

Thanks

Best regards,

Haven Tang

GCDAsyncUDPSocket crash on intensive data rate

Hi,

I made some high data rate test with GCDAsyncUDPSocket class using a copy of UdpEchoServer (with small modification) and a new simple Client. What I saw is that with high data rate both client and server crashes. Adding a simple semaphore is getting better, but do not solve. The problem is in the receiving that in the real application is not under my control.
Running both apps on the same machine from Xcode and starting server and clicking send on client, the problem happen
most of the time on the first test.

AsyncSocket couldn't determine IP version of socket

I'm trying to use the library in an iPad application and whenever I try to use an AsyncSocket, I get the following error:

2012-03-02 17:21:40.407 Sucursales2[11862:707] AsyncSocket 0x4464dc0 couldn't get socket from streams, Error Domain=AsyncSocketErrorDomain Code=-1 "General CFSocket error" UserInfo=0x595590 {NSLocalizedDescription=General CFSocket error}. Disconnecting.
Error: : No such file or directory

I'm running an iPad 2 3G+WiFi with 5.0.1

The weird thing is that I copied both the AsyncSocket classes and a client class to my new app from a previous project in which AsyncSocket worked perfectly without any issues.

I thought that it would be a matter of the new app being compiled with SDK 5.0, so I downloaded the latest archive from github, but still experiencing the problem.

Any ideas on what it might be?

PS; I'm NOT using ARC for this project.

readDataWithTimeout: reads are sometimes returning truncated data

I noticed my reads for all data were being truncated (not every time, but anecdotally it was more likely on longer reads)

So after noticing there were different code paths for the three different kinds of reads, I just changed the logic of my client/server protocol to add a ZeroData at the end of transmission and to receive using readData:toData, thus forcing me into the read-to-terminator code path. Now my reads always return complete data.

If I find time to track this bug down, I will, but thought I should report it.

One possibility I didn't consider until just now: if socket:didReadData:withTag: is called for each "chunk" of data in the read, with the expectation that the delegate will handle the partials, then this is functioning as expected, and the documentation needs to be updated.

GCDAsyncSocket stops reading

Hi Robbie,
I have been using AsyncSocket for well over a year now in our product. It has worked really well for us, great work!. I am switching over to GCDAsyncSocket now and am experiencing an issue reading. Once I connect to the server and start reading/writing my didReadData delegate stops being called after 20 seconds or so. There is a another user experiencing this issue in the google group: http://groups.google.com/group/cocoaasyncsocket/browse_thread/thread/7fb3004aa35c6f32. If I put a NSLog(@".") in the delegate then I continue receiving data. Any thoughts?
Thanks,
Chris

Client certificate authentication

GCDAsyncSocket does not allow client certificate authentication, even if the certificate is transmitted by the client.
This is because SecureTransport has a default authentication requirement set to kNeverAuthenticate and, as far as I know, there's no way to change this with GCDAsyncSocket.
Because of that, SSLCopyPeerCertificates(sslContext, &certs) will get you a nil object.

Simple patch below

GCDAsyncSocket.h:
extern NSString *const GCDAsyncSocketSSLClientSideAuthentication;

GCDAsyncSocket.m:
NSString *const GCDAsyncSocketSSLClientSideAuthentication = @"GCDAsyncSocketClientSideAuthentication";

in maybeStartTls:

// Configure SSLContext from given settings
//
// Checklist:
// 1. kCFStreamSSLPeerName
// 2. kCFStreamSSLAllowsAnyRoot
// 3. kCFStreamSSLAllowsExpiredRoots
// 4. kCFStreamSSLValidatesCertificateChain
// 5. kCFStreamSSLAllowsExpiredCertificates
// 6. kCFStreamSSLCertificates
// 7. kCFStreamSSLLevel
// 8. GCDAsyncSocketSSLCipherSuites
// 9. GCDAsyncSocketSSLDiffieHellmanParameters
// 10. GCDAsyncSocketSSLClientSideAuthentication

...
// 10. GCDAsyncSocketSSLClientSideAuthentication
if (isServer) {
value = [tlsSettings objectForKey:GCDAsyncSocketSSLClientSideAuthentication];
NSNumber *sslAuthNumber = (NSNumber *)value;
int sslAuth = [sslAuthNumber intValue];
if (sslAuth == kTryAuthenticate
|| sslAuth == kAlwaysAuthenticate
|| sslAuth == kNeverAuthenticate)
status = SSLSetClientSideAuthenticate(sslContext, sslAuth);
if (status != noErr)
{
[self closeWithError:[self otherError:@"Error in SSLSetClientSideAuthenticate"]];
return;
}
}

Then just set the tlsSettings (on the server side only) like this:
[tlsSettings setObject:[NSNumber numberWithInt:kAlwaysAuthenticate] forKey:(NSString *)GCDAsyncSocketSSLClientSideAuthentication];

Socket closed by remote peer after 2 minutes

In my iOS application I'm communicating with a STAR printer via a socket on port 9101 (discovered via NSNetServices). I have been able to reduce my code a lot by using the GCDAsyncSocket library (thanks!)

The STAR printer is continuously sending me its status (about 2 times a second). I'm using readDataWithTimeout and didReadData to process the status communicated by the printer. Everything is working fine.

However after exactly two minutes the connection is disconnected with error: Socket closed by remote peer.

I didn't have this problem with my own implementation based on NSNetService getInputOutputstream. It seems that GCDAsyncSocket assumes the connection is gone even though it isn't? I've tried AsyncSocket as well instead of GCDAsyncSocket: same problem.

How can I determine what is closing the socket?

I'm testing on the iPad simulator targeted at iOS 5.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.