Building a Server/Client application in Cocoa

前端 未结 3 1232
無奈伤痛
無奈伤痛 2020-12-09 21:03

I built a fairly simple program that watches a folder, manipulates files as they are added, and gives a simple progress view of whats going on. The folder is watched via a s

相关标签:
3条回答
  • 2020-12-09 21:51

    This, unfortunately, is a place where Cocoa is pretty weak. Forget about WebObjects (Apple has). You probably should forget about Distributed Objects. There isn't really a built-in client/server solution on Mac. iOS has some decent peer-to-peer stuff, but it's still pretty useless for client/server.

    My recommendation is to use a simple REST API. Build your server with cocoahttpserver. Build your client with NSURLConnection or ASIHTTPRequest. Keep it simple. I like JSON for the protocol. YAJL has worked well for me, but for something really simple, there are lots of options.

    0 讨论(0)
  • 2020-12-09 21:58

    I would suggest using TCP for something like this. Since (I assume) you are writing this software for BSD (Mac OS X and iPhone are both BSD) you can use BSD C sockets, or an Objective-C wrapper for this. One good library for a client is CocoaAsyncSocket. I personally have written a lightweight Objective-C socket class for TCP networking called SocketKit. Usage of this library is something as follows:

    // open a connection
    SKTCPSocket * socket = [[SKTCPSocket alloc] initWithRemoteHost:@"SERVER_IP" port:SERVER_PORT];
    // write data
    [socket writeData:someData];
    // read data
    NSData * someData = [socket readData:4];
    // close the socket
    [socket close];
    [socket release];
    

    From a server standpoint, you can listen on a port using the SKTCPSocketServer class:

    SKTCPSocket * aSocket = nil;
    SKTCPSocketServer * server = [[SKTCPSocketServer alloc] initListeningOnPort:1337];
    @try {
        [server listen];
        while ((aSocket = (SKTCPSocket *)[server acceptConnection]) != nil) {
            // do something with aSocket
            [aSocket close];
        }
    } @catch (NSException * e) {
        NSLog(@"Exception : %@", e);
    }
    [server stopServer];
    [server release];
    

    Of course using TCP sockets means writing your own network protocol. A simple example would be sending a four byte length field, followed by the data of an NSDictionary or something of that nature. This could allow you to accomplish something similar to a very basic Distributed Objects system.

    0 讨论(0)
  • 2020-12-09 21:58

    Why not take a look at Bonjour for zero-configuration networking (i.e. so you don't have to find the IP address of your server)?

    Since Bonjour is also supported on Windows and iOS (iPhone/iPad) you can even make your app multi-platform (e.g. server on Windows and Mac client or vice versa) or even have an iPhone act as a client of your server (don't know if this makes sense in your case but I'm just suggesting).

    0 讨论(0)
提交回复
热议问题