[英]Creating a TCP Socket connection and keep the connection open across several views
我已經使用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庫打開我的Sockets連接。 謝謝您的幫助!
*編輯*
根據下面的答案,這就是我到目前為止要做的事情:
SocketConnection.h
#import <Foundation/Foundation.h>
@interface SocketConnection : NSObject
{
}
+ (SocketConnection *)getInstance;
@end
SocketConnection.m
靜態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
我仍然沒有弄清楚單例類如何被調用。 我使用上面的代碼啟動了我的應用,但未連接到服務器。 有任何想法嗎?
謝謝!
您應該創建一個單例類來保持連接,如以下代碼所示:
h文件:
#import <Foundation/Foundation.h>
@interface SocketConnection : NSObject
{
}
+ (SocketConnection *)getInstance;
@end;
m文件:
#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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.