我已成功使用TCP套接字从iPhone连接到服务器(这是一台Windows机器)。目前,我正在使用一个按钮来执行以下代码:
while(1)
{
Socket *socket;
int port = 11005;
NSString *host = @"9.5.3.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;
}
}
这是最简单的部分......我正在尝试在应用加载后立即建立套接字连接。我尝试将此代码放在我的viewDidLoad中,但循环是无限的,视图永远不会加载。我的项目中有几个视图,我想打开连接,在所有视图中始终保持连接打开。
目标:
我仍然是iOS开发的新手,所以我尽可能地欣赏它。应该注意的是,我正在使用SmallSockets库来打开我的套接字连接。谢谢你的帮助!
*编辑*
基于下面的答案,这是我到目前为止所做的事情:
SocketConnection.h
#import <Foundation/Foundation.h>
@interface SocketConnection : NSObject
{
}
+ (SocketConnection *)getInstance;
@end
SocketConnection.m
static SocketConnection * sharedInstance = nil;
@implementation SocketConnection
- (id)init
{
self = [super init];
if (self)
{
while(1)
{
Socket *socket;
int port = 11005;
NSString *host = @"9.5.3.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;
}
}
}
return self;
}
+ (SocketConnection *)getInstance
{
@synchronized(self)
{
if (sharedInstance == nil)
{
sharedInstance = [[SocketConnection alloc] init];
}
}
return sharedInstance;
}
@end
我还没弄明白如何调用单例类。我使用上面的代码启动了我的应用程序,但它没有连接到服务器。有什么想法吗?
谢谢!
答案 0 :(得分:4)
您应该创建一个单例类来保持您的连接,如下面的代码:
h file:
#import <Foundation/Foundation.h>
@interface SocketConnection : NSObject
{
}
+ (SocketConnection *)getInstance;
@end;
m file:
#import "SocketConnection.h"
static SocketConnection *sharedInstance = nil;
@implementation SocketConnection
- (id)init
{
self = [super init];
if (self) {
}
return self;
}
+ (SocketConnection *)getInstance
{
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[SocketConnection alloc] init];
}
}
return sharedInstance;
}
@end;