Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

objective c - Building a Server/Client application in Cocoa

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 subclass of NSOperation that passes information in an NSDictionary to my progress view, via the NSNotificationCenter.

Now I need to break things up and run the watched folder/processing part on my server, and build a client to monitor the progress from multiple workstations. My problem is I don't know how to accomplish this and my searches aren't really helping me.

It seems I'm getting a lot of out dated solutions (WebObjects, Portable Distributed Objects) or incomplete information. It seems like I'd want to use NSStream to pass data back and forth, but everything I find on NSStream looks like it's set up for client side because it's looking for an IP address. What would be the best way to go about setting up both a server, and a client to connect to it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...