代码之家  ›  专栏  ›  技术社区  ›  Mark

iPhone TCP/IP套接字服务器/客户端程序

  •  23
  • Mark  · 技术社区  · 16 年前

    我的目标

    就是要构建一个可以在Mac OS X 10.4+及更高版本上运行的服务器,并将其移植到Windows XP/Vista(目前还不知道如何做到这一点,但这是以后的问题)。

    然后,让iPhone成为能够查看运行服务器的计算机名称的客户端(通过WiFi)。然后,iPhone用户可以选择要连接到该计算机上服务器的计算机名。

    之后,他们可以互相发送简单的短信。例如,iPhone发送“敲门敲门”,服务器响应“谁在那里?”。或者一个简单的客户端:“Ping”,服务器响应“Pong”就可以了。

    出身背景

    我以前使用过套接字,但只有在VisualBasic6中使用WINSOCKET.dll时,创建TCP/IP服务器才非常容易。

    server.host = localhost;
    server.port = 12203;
    server.listen(); 
    

    对于客户端,我只需要执行以下操作即可连接。

    client.connect(localhost, 12203);
    

    有一些回调可用,如connect、close、dataArrival等,我可以用它们来做任何我想做的事情。

    问题

    有没有人可以指导我阅读教程或在iPhone上有两个按钮的地方发布代码。[启动服务器]和[连接到服务器],其中第一个将在某个端口上启动TCP/IP服务器,第二个连接到该端口。

    那真的很有帮助。但也许我在这里要求的太多了。

    3 回复  |  直到 13 年前
        1
  •  19
  •   tony gil    13 年前

    this tutorial 创建一个聊天示例应用程序工作得非常好,非常简单(任何iphone noob,像我一样,都可以让它工作,即使在模拟器模式下,它连接到外部套接字服务器)。

    我把它改装成了我的socket服务器,它工作起来很有魅力。这是测试代码,所以没有真正的问题。它只发送一条消息(您的登录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
    

    您的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;
    

    this video tutorial

    NOOBS ONLY 2:此套接字将在XCODE的控制台窗格中输出。在xcode窗口的右上角,单击隐藏或显示调试区域(如有必要,请寻求帮助)。

    在带有2GB内存的macbook上构建并测试(模拟器和设备),使用雪豹xcode 4.2。

        2
  •  3
  •   Mike Ohlsen    13 年前

    Cocoa Async Socket

    网站上还有一个基本的示例项目可以帮助您开始。我在使用该框架方面取得了很大的成功。

        3
  •  1
  •   Chris Kline    16 年前

    推荐文章