我正在尝试使用SmallSockets库来创建TCP套接字连接。目前,我正在使用一个按钮来测试我与iPhone的服务器连接。这是我的代码:
-(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;
}
}
}
当我按下按钮时,我的应用程序冻结了。它冻结了以下函数(它是SmallSockets库的一部分):
- (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;
}
该应用程序在该行冻结:[data appendBytes:readBuffer length:count];然后它在同一行说:线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x5d18c48b)。我在输出中看到的只是(lldb)绿色字母。一旦客户端连接,服务器就会向客户端发送一个4字节的数据包。
如果有人能说明我的应用程序崩溃的原因,我真的很感激。我现在已经敲了几个小时试图找出问题所在。
谢谢!
答案 0 :(得分:0)
我不知道这是否是正确的答案,但我要做的第一件事就是立即保留套接字。如果您对套接字有问题,请在异常处理程序中将其释放。