Jayprakash Dubey
Jayprakash Dubey

Reputation: 36447

How to get response from server using socket connection in iOS?

I want to fetch a response from server after successfully establishing socket connection. I have used source code from GitHub Socket source code.

I have placed below code on button click:

 NSString *outgoingMessage = @"Some string to be sent to server";
 NSData *messageData = [outgoingMessage dataUsingEncoding:NSUTF8StringEncoding]
 const void *bytes = [messageData bytes];
 uint8_t *uint8_t_message = (uint8_t*)bytes;

 [outputStream write:uint8_t_message maxLength:strlen([outgoingMessage cStringUsingEncoding:[NSString defaultCStringEncoding]])];

 while (![inputStream hasBytesAvailable]) {
            usleep(1);
  } 
  uint8_t buffer[1024];
  [inputStream read:buffer maxLength:1023];
  NSString *outputString = [NSString stringWithUTF8String:(char *)buffer];

  NSLog(@"outputString : %@ ",outputString);

I'm getting an empty response. Also after debugging my code doesn't enters NSStreamEventHasBytesAvailable case in

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode { .. }

What might be fix for it?

Upvotes: 0

Views: 513

Answers (1)

l3bel
l3bel

Reputation: 91

I suggest you use an Objective-C WebSocket client, SocketRocket to name one: https://github.com/square/SocketRocket

A good and simple example of using the Websocket client can be found here: http://www.elabs.se/blog/66-using-websockets-in-native-ios-and-android-apps

Upvotes: 1

Related Questions