I am trying to use the SmallSockets library to create a TCP socket connection. Currently, I’m using a button to simply test my connection to a server from my iPhone. Here is what my code looks like:
-(IBAction)btnConnect:(id)sender
{
bool loopConnection = true;
while(loopConnection == true)
{
Socket *socket;
int port = 11005;
NSString *host = @"199.5.83.63";
socket = [Socket socket];
@try
{
NSMutableData *data;
[socket connectToHostName:host port:port];
[socket readData:data];
// [socket writeString:@"Hello World!"];
//** Connection was successful **//
[socket retain]; // Must retain if want to use out of this action block.
}
@catch (NSException* exception)
{
NSString *errMsg = [NSString stringWithFormat:@"%@",[exception reason]];
NSLog(errMsg);
socket = nil;
}
}
}
When I press the button, my app freezes. It freezes on the following function (which is part of the SmallSockets library):
- (int)readData:(NSMutableData*)data
//
// Append any available data from the socket to the supplied buffer.
// Returns number of bytes received. (May be 0)
//
{
ssize_t count;
// data must not be null ptr
if ( data == NULL )
[NSException raise:SOCKET_EX_INVALID_BUFFER
format:SOCKET_EX_INVALID_BUFFER];
// Socket must be created and connected
if ( socketfd == SOCKET_INVALID_DESCRIPTOR )
[NSException raise:SOCKET_EX_BAD_SOCKET_DESCRIPTOR
format:SOCKET_EX_BAD_SOCKET_DESCRIPTOR];
if ( !connected )
[NSException raise:SOCKET_EX_NOT_CONNECTED
format:SOCKET_EX_NOT_CONNECTED];
// Request a read of as much as we can. Should return immediately if no data.
count = recv(socketfd, readBuffer, readBufferSize, 0);
if ( count > 0 )
{
// Got some data, append it to user's buffer
[data appendBytes:readBuffer length:count];
}
else if ( count == 0 )
{
// Other side has disconnected, so close down our socket
[self close];
}
else if ( count < 0 )
{
// recv() returned an error.
if ( errno == EAGAIN )
{
// No data available to read (and socket is non-blocking)
count = 0;
}
else
[NSException raise:SOCKET_EX_RECV_FAILED
format:SOCKET_EX_RECV_FAILED_F, strerror(errno)];
}
return count;
}
The app freezes on the line: [data appendBytes:readBuffer length:count]; and then it says on the same line: Thread 1:EXC_BAD_ACCESS (code=1, address=0x5d18c48b). All I see in the output is (lldb) in green letters. As soon as a client connects, the server sends a 4 byte packet to the client.
If anyone could shed some light as to why my app is crashing here, I’d really appreciate it. I’ve been banging my head for a couple hours now trying to figure out what the issue is.
Thanks!
I don’t know if this is the right answer or not, but the first thing I would do is retain the socket right away. If you have a problem with the socket, then release it in the exception handler.