Socket Programming in Objective-C - objective-c

currently I am wanting to program a chat server. I am having trouble really understanding the documentations though.
Currently, this is my code, basically extracted from the developer library:
#import "ServerSide.h"
#implementation ServerSide
#synthesize socket;
#synthesize socketAddress;
#synthesize handleConnect;
#synthesize portNumber;
- (id)init{
self = [super init];
if (self) {
self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, handleConnect, NULL);
}
return self;
}
- (void) bind {
memset(&socketAddress, 0, sizeof(socketAddress));
socketAddress.sin_len = sizeof(socketAddress);
socketAddress.sin_family = AF_INET; /* Address family */
socketAddress.sin_port = htons(self.portNumber); /* Or a specific port */
socketAddress.sin_addr.s_addr= INADDR_ANY;
CFDataRef sincfd = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&socketAddress, sizeof(socketAddress));
CFSocketSetAddress(socket, sincfd);
CFRelease(sincfd);
}
- (void) listen {
CFRunLoopSourceRef socketsource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), socketsource, kCFRunLoopDefaultMode);
CFSocketGetNative(socket);
}
Now, 'handleconnect' is a CFSocketCallBack ivar with no initialization.
Now I have seen others use different implementations to creating a socket server but this was the one from the docs and I would like to build on top of that.
I am currently attempting to connect to the server but it looks like this doesn't even open a socket. I can't seem to connect to it through terminal using telnet localhost 'port#' either.
Heres the client implementation:
#import "Client.h"
#implementation Client
#synthesize host;
#synthesize port;
#synthesize readStream;
#synthesize writeStream;
#synthesize inputStream;
#synthesize outputStream;
- (void)setup {
NSLog(#"Setting up connection to %# : %i", [[NSURL URLWithString:host] absoluteString], port);
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)[[NSURL URLWithString:host] host], port, &readStream, &writeStream);
if(!CFWriteStreamOpen(writeStream)) {
NSLog(#"Error, writeStream not open");
return;
}
}
- (void)open {
NSLog(#"Opening streams.");
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)close {
NSLog(#"Closing streams.");
[inputStream close];
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
[outputStream setDelegate:nil];
inputStream = nil;
outputStream = nil;
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
NSLog(#"Stream triggered.");
switch(event) {
case NSStreamEventHasSpaceAvailable: {
if(stream == outputStream) {
NSLog(#"outputStream is ready.");
}
break;
}
case NSStreamEventHasBytesAvailable: {
if(stream == inputStream) {
NSLog(#"inputStream is ready.");
uint8_t buf[1024];
unsigned int len = 0;
len = (int)[inputStream read:buf maxLength:1024];
if(len > 0) {
NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
[data appendBytes:(const void *)buf length:len];
[self readIn:[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]];
data = nil;
}
}
break;
}
default: {
NSLog(#"Stream is sending an Event: %lu", event);
break;
}
}
}
- (void)readIn:(NSString *)s {
NSLog(#"Reading in the following:");
NSLog(#"%#", s);
}
- (void)writeOut:(NSString *)s {
uint8_t *buf = (uint8_t *)[s UTF8String];
[outputStream write:buf maxLength:strlen((char *)buf)];
NSLog(#"Writing out the following:");
NSLog(#"%#", s);
}
#end
I run the server on a specified port, then tell the client to connect to the specified host and port number.
But now how do I pass data in the socket I have opened...
I don't expect some large explanation, but if someone could give me a better understanding of what needs to be done to further this implementation, I'd greatly appreciate it.

Related

What is the reason that AFMultipartBodyStream does not support scheduleInRunLoop mechanism?

Though AFMultipartBodyStream of AFNetworking lib is a subclass of NSStream conforming to NSStreamDelegate protocol, it could not be processed as with standard way of a regular NSStream. Namely, AFMultipartBodyStream could not be handled with stream event. I looked into the code of AFMultipartBodyStream, and found that it intentionally disabled the scheduleInRunLoop method of NSInputStream abstract class:
- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
Any specific reason? Is it a way to make it support the standard stream event mechanism so that the stream data handling can be done asynchronously with stream:handleEvent: event handler?
After studying the implementation of AFMultipartBodyStream, I noticed that the way of current implementation could not support the asynchronous way of regular stream IO handling. I then enhanced AFMultipartBodyStream to provide a stream which was connected with the internal multipart data structure, and thus the holder of this AFMultipartBodyStream can handle the multipartbody data as the regular stream which can be scheduled in the runloop. below code snippet shows the main idea:
-(NSInputStream *)inputStream {
// If _inputStream has not been connected with HTTPBodyParts data, establish the connection
if (!_inputStream) {
NSParameterAssert([self.HTTPBodyParts count] != 0);
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFIndex bufferSize = self.contentLength;
CFStreamCreateBoundPair(NULL, &readStream, &writeStream, bufferSize);
_inputStream = (__bridge_transfer NSInputStream *)readStream;
_outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[_outputStream setDelegate:self];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(#"\n====in async block of inputStream....====\n");
[self->_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self open];
[self->_outputStream open];
NSInteger totalBytesSent = self.contentLength;
while (totalBytesSent > 0 && [self->_outputStream hasSpaceAvailable]) {
uint8_t buffer[1024];
NSInteger bytesRead = [self read:buffer maxLength:1024];
totalBytesSent -= bytesRead;
NSLog(#"\n====buffer read (%ld): [%s]====\n", (long)bytesRead, buffer);
if (self.streamError || bytesRead < 0) {
break;
}
NSInteger bytesWritten = [self->_outputStream write:buffer maxLength:(NSUInteger)bytesRead];
if (self->_outputStream.streamError || bytesWritten < 0) {
NSLog(#"\n====Socket write failed[%#]====\n", self->_outputStream.streamError);
break;
}
if (bytesRead == 0 && bytesWritten == 0) {
break;
}
}
[self->_outputStream close];
[self->_outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
});
}
return _inputStream;
}
// Added
- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{
// Setup the input stream for body stream data consuming
NSInputStream *inputStream = [self inputStream];
NSParameterAssert(inputStream == self.inputStream);
[inputStream setDelegate:self.delegate_];
[inputStream scheduleInRunLoop:aRunLoop forMode:mode];
[inputStream open];
}
// Added
- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{
if (_inputStream) {
[_inputStream setDelegate:[self delegate]];
[_inputStream removeFromRunLoop:aRunLoop forMode:mode];
[_inputStream close];
}
}

Objective c - Writing image file to ip address

Experts:
I've been researching all morning on how to write an image file to another computer via IP Address. Do I really need to create sockets, set delegates, schedule a run loop, check space available, and all that hoopla? Really? Can't I just save the file to a URL using the IP Address and default port?
I'm asking this question because I'm not making much progress on my own and I know the minute I hit Post Your Question I'll find some useful information. But in case that does not happen, please reply. Any help is appreciated.
This is the code I have and I think I'm on the wrong track:
#import "TESTtcpController.h"
#interface TESTtcpController()
#property (nonatomic, strong)NSInputStream *inputStream;
#property (nonatomic, strong)NSOutputStream *outputStream;
//void CFStreamCreatePairWithSocketToHost (
// CFAllocatorRef alloc,
// CFStringRef host,
// UInt32 port,
// CFReadStreamRef *readStream,
// CFWriteStreamRef *writeStream
// );
#end
#implementation TESTtcpController
+ (void)sendFile:(UIImage *)image
{
UInt32 port = 80;
NSString *ipAddress = #"10.10.10.10";
TESTtcpController *tcpController = [[TESTtcpController alloc] init];
[tcpController connect:port ipAddress:ipAddress];
[tcpController postFile:image];
[tcpController disconnect];
tcpController = nil;
}
-(void)connect:(UInt32)port ipAddress:(NSString *)ipAddress
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ipAddress, port, &readStream, &writeStream);
self.inputStream = (__bridge NSInputStream *)readStream;
self.outputStream = (__bridge NSOutputStream *)writeStream;
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
NSLog(#"input stream id %#", self.inputStream);
/* Store a reference to the input and output streams so that
they don't go away.... */
}
- (void)postFile:(UIImage *)image
{
}
- (void)dataSending:(NSString*)data {
if(self.outputStream) {
if(![self.outputStream hasSpaceAvailable])
return;
NSData *_data=[data dataUsingEncoding:NSUTF8StringEncoding]; int data_len = [_data length];
uint8_t *readBytes = (uint8_t *)[_data bytes];
int byteIndex=0;
unsigned int len=0;
while (TRUE) {
len = ((data_len - byteIndex >= 40960) ? 40960 : (data_len-byteIndex));
if(len==0)
break;
uint8_t buf[len]; (void)memcpy(buf, readBytes, len);
len = [self.outputStream write:(const uint8_t *)buf maxLength:len]; byteIndex += len;
readBytes += len; }
}
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
switch(eventCode) {
case NSStreamEventNone:
break;
case NSStreamEventOpenCompleted:
break;
case NSStreamEventHasBytesAvailable:
break;
case NSStreamEventHasSpaceAvailable:
// {
// uint8_t *readBytes = (uint8_t *)[_data mutableBytes];
// readBytes += byteIndex; // instance variable to move pointer
// int data_len = [_data length];
// unsigned int len = ((data_len - byteIndex >= 1024) ?
// 1024 : (data_len-byteIndex));
// uint8_t buf[len];
// (void)memcpy(buf, readBytes, len);
// len = [stream write:(const uint8_t *)buf maxLength:len];
// byteIndex += len;
// break;
// }
case NSStreamEventErrorOccurred:
break;
case NSStreamEventEndEncountered:
break;
// continued ...
}
}
-(void)disconnect{
NSLog(#"disconnect method called");
NSStreamStatus socketStatus = [self.outputStream streamStatus];
int status = socketStatus;
NSLog(#"Stream Status is %i", status);
if (status == 2) {
[self.inputStream close];
[self.outputStream close];
NSLog(#"Socket Closed");
}
}
- (void)deallocMe
{
[TESTtcpController dealloc];
}
#end
You should use the AFNetworking library. Image uploads will be trivial. Read about AFNetworking here: http://cocoadocs.org/docsets/AFNetworking/2.0.0/
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

NSOutputStream crashing with Bad Access after write (Objective-c)

I have been trying to get a basic TCP client up and running for my iOS application but have run into a block which i cannot seem to work my head around.
So far i can connect, send a message which is received on the server side but then my app crashes.
Client.h
#import <Foundation/Foundation.h>
#interface Client : NSObject <NSStreamDelegate>
{
NSInputStream *inputStream;
NSOutputStream *outputStream;
}
-(void)initNetworkCommunication;
-(void)send:(NSString*)message;
#end
Client.m
#import "Client.h"
#implementation Client
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"10.0.1.51", 7769, &readStream, &writeStream);
inputStream = ( NSInputStream *)CFBridgingRelease(readStream);
outputStream = ( NSOutputStream *)CFBridgingRelease(writeStream);
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)send:(NSString*)message
{
NSData *data = [[NSData alloc] initWithData:[message dataUsingEncoding:NSUTF8StringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(#"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(#"server said: %#", output);
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
NSLog(#"End Encountered!");
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
theStream = nil;
break;
default:
NSLog(#"Unknown event");
}
}
#end
The output in the console is
2013-10-03 17:01:38.542 MMORPG[6076:70b] stream event 1
2013-10-03 17:01:38.543 MMORPG[6076:70b] Stream opened
2013-10-03 17:01:43.495 MMORPG[6076:70b] stream event 4
2013-10-03 17:01:43.495 MMORPG[6076:70b] Unknown event
It seems like, my message is sent, i receive stream event #4 and then i get a bad access crash. The problem is i have no idea what its having trouble accessing?
Any help would be greatly appreciated!
The problem is that NSStream keeps an assign/unsafe_unretained reference to its delegate. If the delegate is released before the stream is closed and released, the stream will try to call methods on its now deallocated delegate, causing a crash. The solution is to either make sure some other object has a strong reference to the client, preventing its early deallocation, or else make sure you close and release the stream before its delegate is deallocated.

NSInputStream not opening stream/ How to post data when setting up stream

What I am trying to do: I have a url request (post) where I send some information to a api server which then starts streaming data in bytes to me.
1) How do I post data when trying to set up a stream as right now I am just using a url, can I incorporate a NSURLRequest some how?
2) Why isnt my stream even opening (streamStatus returns 0) and thus - (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode never being called? , this is my best attempt and for the most part following this Guide
- (void)setUpStreamFromURL:(NSURL *)path {
// iStream is NSInputStream instance variable
iStream = [[NSInputStream alloc] initWithURL:path];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
NSLog(#"Stream Open: %lu",[iStream streamStatus]); //return 0
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSLog(#"Streaming");
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if(!_data) {
_data = [[NSMutableData data] init];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len) {
[_data appendBytes:(const void *)buf length:len];
NSLog(#"DATA BEING SENT : %#", _data);
// bytesRead is an instance variable of type NSNumber.
// [bytesRead setIntValue:[bytesRead intValue]+len]; //getting error that setInt value is not part of NSNumber, and thats true so not sure what to do about it, but this isn't the issue.
} else {
NSLog(#"no buffer!");
}
break;
}
case NSStreamEventEndEncountered:
{
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
stream = nil; // stream is ivar, so reinit it
break;
}
// continued ...
}
}
also incase it helps, my header file:
#import <Foundation/Foundation.h>
#import "Login.h"
#interface Stream : NSStream <NSStreamDelegate> {
NSMutableArray *searchIdList;
NSInputStream *iStream;
NSNumber *bytesRead;
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode ;
-(id)initWithLoginObject:(Login *)log;
#property NSMutableData *data;
#end
You can't use NSURLRequest in Stream.
To create a request you can use this.
request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"),(CFURLRef) url, kCFHTTPVersion1_1);
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("User-Agent"), CFSTR("MSControl-US"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Content-Type"), CFSTR("application/json"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Keep-Alive"));
After that you can create the stream using
readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request)
or if you already have an opened stream you can serialize your request With :
NSData *data = (NSData *)CFHTTPMessageCopySerializedMessage(request);
and send with This:
length = [data length];
CFWriteStreamWrite((CFWriteStreamRef)outStream,data,lenght);
Hope this help

cant read data from tcp port

i have written code for reading data from tcp port 3000
- (BOOL)connect
{
int cIter = 0;
while(cIter++<5)
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
#try{
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)M_CONNECT_HOST, M_CONNECT_PORT, &readStream, &writeStream);
}
#catch (NSException *ex) {
}
if(readStream!=nil && writeStream!=nil)
{
m_sin = (__bridge NSInputStream *)readStream;
m_sout = (__bridge NSOutputStream *)writeStream;
[m_sin setDelegate:self];
[m_sout setDelegate:self];
[m_sin scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[m_sout scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[m_sin open];
[m_sout open];
return true;
}
}
return false;
}
When i write to tcp output stream its working but when i try to read from the tcp input stream its not reading i mean my
[m_sin read:t maxlength:10];
is always returning -1 (where m_sin is my input stream)
And i m passing the data to the tcp port by terminal
please Help me
Implement the handleEvent and check it out the eventCode
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
switch (eventCode) {
case NSStreamEventOpenCompleted:
NSLog(#"stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (aStream == inputStream) {
// read it in
unsigned int len = 0;
len = [inputStream read:buf maxLength:1019];
buf[len] = '\0';
if(!len) {
if ([aStream streamStatus] != NSStreamStatusAtEnd){
NSLog(#"Failed reading data from peer");
}
} else {
//I am reading UIImage here
NSData *data = [NSData dataWithBytes:(const void *)buf length:1019];
UIImage *image = [UIImage imageWithData:data];
self.transferedimage.image = image;
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"stream ErrorOccurred");
break;
case NSStreamEventEndEncountered:
NSLog(#"stream EndEncountered");
break;
default:
NSLog(#"stream UnKnown");
break;
}
}