Mar*_*ark 23 sockets iphone connection communication
我在这个网站上已经阅读了很多关于这个主题的问题,但他们并没有安静地回答我的问题.如果你不能###关于我的目标或背景,请跳过这个问题.
我的目标
是构建一个可以在Mac OS X 10.4及更高版本上运行的服务器,将其移植到Windows XP/Vista(不知道如何做到这一点,但这是以后的问题).
然后让iPhone成为能够查看运行服务器的计算机名称(通过WiFi)的客户端.然后,iPhone的用户可以选择计算机名称以连接到该计算机上的服务器.
之后,他们可以相互发送简单的短信.例如,iPhone发送'Knock Knock'并且服务器响应'谁在那里?'.或者一个简单的客户端:'Ping',服务器响应'Pong'就行了.
背景
我以前使用套接字,但只有在使用WINSOCKET.dll的Visual Basic 6中才能很容易地创建TCP/IP服务器.
server.host = localhost;
server.port = 12203;
server.listen();
Run Code Online (Sandbox Code Playgroud)
对于客户端,我只需要执行以下连接.
client.connect(localhost, 12203);
Run Code Online (Sandbox Code Playgroud)
有一些回调可用,如connect,close,dataArrival等,我可以用来做我想做的任何事情.
也许对于iPhone来说,有为它编写的库,但是自己创建这个简单的应用程序是否很难?在做了一些研究后,我明白我必须查看CFNetwork,CFHost,CFSocket,CFStream等领域.
题
是否有人可以指导我阅读教程或发布iPhone上有两个按钮的代码.[Start Server]和[Connect to Server],第一个将在某个端口上启动TCP/IP服务器,第二个连接到它.
在建立连接之后,也可能是在服务器收到此消息后向服务器发送简单的"Ping"消息的代码,并向客户端发送"Pong"消息.
这真的很有帮助.但也许我在这里要求很多.
ton*_*gil 18
这个教程创建一个聊天示例应用程序非常好,非常简单(任何iphone noob,像我一样,可以使它工作,即使在模拟器模式下,它连接到外部套接字服务器).
我改编它来谈论我的套接字服务器,它就像一个魅力.这是测试代码,所以没有真正关心松散的目的.它只发送一条消息(您的登录ID)并收到回复,它在控制台中显示.
//
// ViewController.m
// zdelSocketTest01a
//
//
#import "ViewController.h"
@implementation ViewController
@synthesize inputNameField;
@synthesize joinView;
- (void)initNetworkCommunication {
uint portNo = 5555;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"227.3.4.56", portNo, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initNetworkCommunication];
messages = [[NSMutableArray alloc] init];
}
- (void)viewDidUnload
{
[self setInputNameField:nil];
[self setJoinView:nil];
[self setJoinView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)joinChat:(id)sender {
NSString *response = [NSString stringWithFormat:@"logon,%@", inputNameField.text];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
/*
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(@"stream event %i", streamEvent);
}
*/
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
typedef enum {
NSStreamEventNone = 0,
NSStreamEventOpenCompleted = 1 << 0,
NSStreamEventHasBytesAvailable = 1 << 1,
NSStreamEventHasSpaceAvailable = 1 << 2,
NSStreamEventErrorOccurred = 1 << 3,
NSStreamEventEndEncountered = 1 << 4
};
uint8_t buffer[1024];
int len;
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened now");
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"has bytes");
if (theStream == inputStream) {
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"server said: %@", output);
}
}
}
} else {
NSLog(@"it is NOT theStream == inputStream");
}
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"Stream has space available now");
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
default:
NSLog(@"Unknown event %i", streamEvent);
}
}
/*
- (void) messageReceived:(NSString *)message {
[messages addObject:message];
[self.tView reloadData];
}
*/
@end
Run Code Online (Sandbox Code Playgroud)
您的ViewController.h文件将包含
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <NSStreamDelegate>
@property (weak, nonatomic) IBOutlet UITextField *inputNameField;
@property (weak, nonatomic) IBOutlet UIView *joinView;
- (IBAction)joinChat:(id)sender;
@end
NSInputStream *inputStream;
NSOutputStream *outputStream;
NSMutableArray * messages;
Run Code Online (Sandbox Code Playgroud)
仅限NOOBS:您必须通过按CONTROL并将对象拖动到代码窗口来链接按钮和文本字段.当您这样做时,将自动创建上面的属性.如果你感到难过,请查看此视频教程
NOOBS ONLY 2:此套接字将在XCODE的CONSOLE PANE中输出.在xcode窗口的右上角,单击HIDE OR SHOW THE DEBUG AREA(必要时请求帮助).
在具有2GB内存的macbook上构建和测试(模拟器和设备),使用xcode 4.2进行雪豹.