我正在尝试使用 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 (code=1, address=0x5d18c48b)。我在输出中看到的都是绿色字母的 (lldb)。一旦客户端连接,服务器就会向客户端发送一个 4 字节的数据包。
如果有人能解释为什么我的应用程序在这里崩溃,我会非常感激。我已经敲了几个小时的头,试图找出问题所在。
谢谢!