开发者

Switch from Sockets to cocoaasyncsockets (question related to string conversion)

开发者 https://www.devze.com 2023-03-18 18:03 出处:网络
This question is related to a iOS project written in ObjectiveC that makes use of some C++-Headers. I\'m using this method to send messages to a server using TCP. As you can see, there is a c++ metho

This question is related to a iOS project written in ObjectiveC that makes use of some C++-Headers.

I'm using this method to send messages to a server using TCP. As you can see, there is a c++ method called that modifies the string to conform to a specific protocol. This string is written to a stream.

-(void) writeToServer:(NSString*) str 
{   
    int len = [str length];
    const char* in_ = new char[len];
    char* out_ = new char[len];

    in_ = [str UTF8String];

    len = binary8BitStringTo7BitStringEncoding::encode(in_, len, out_);

    uint8_t* test = new uint8_t[len];

    for (int i=0; i<len; ++i) {
        test[i] = out_[i];
    }

    [outputStream write:test maxLength:len];
}

I'm planning to use the cocoaasyncsocket-framework (http://code.google.com/p/cocoaasyncsocket/) instead of dealing with streams directly. Question is: How to achive the same functionality when using this framework?

This is what writing to a server using this framework looks like:

NSString *warningMsg = @"Are you still there?\r\n";
NSData *warningData = [warningMsg dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:warningData withTimeout:-1 tag:WARNING_MSG];

These are the definitions of the two methods used for encoding and decoding

unsigned int decode(const char* string, unsigned int len, char* out);
unsigned int e开发者_开发知识库ncode(const char* string, unsigned int len, char* out);

In fact i'm looking for a way to send the char* (result of the encode method) to the server but i'm unsure about the whole"NSString* to char* to uint8_t* to NSString* conversion.

What is the best way to deal with this kind of conversion to achieve the same result using this framework?

Thanks in advance for your answers and time spent!


I figured it out, the equivalent method looks like this:

-(void) writeToServer:(NSString*) str{

    int len = [str length];
    const char* in_ = new char[len];
    char* out_ = new char[len];

    in_ = [str cStringUsingEncoding:NSASCIIStringEncoding];

    len = binary8BitStringTo7BitStringEncoding::encode(in_, len, out_);

    [socket writeData:[NSData dataWithBytes:out_ length:len] withTimeout:-1 tag:1];

}
0

精彩评论

暂无评论...
验证码 换一张
取 消