Adding client_server NSMachPort example

This commit is contained in:
Karmaz95
2024-12-16 14:35:30 +01:00
parent 5e6daa4a92
commit b735706891
3 changed files with 63 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
CC=clang
FRAMEWORKS=-framework Foundation
all: server client
server: server.m
$(CC) $(FRAMEWORKS) server.m -o server
client: client.m
$(CC) $(FRAMEWORKS) client.m -o client
clean:
rm -f server client

View File

@@ -0,0 +1,19 @@
// client.m
#import <Foundation/Foundation.h>
#import <servers/bootstrap.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
if (argc != 2) return 1;
mach_port_t bp, port;
task_get_bootstrap_port(mach_task_self(), &bp);
bootstrap_look_up(bp, "com.crimson.message_service", &port);
NSMachPort *machPort = [[NSMachPort alloc] initWithMachPort:port];
NSData *data = [[NSString stringWithUTF8String:argv[1]] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *components = [NSMutableArray arrayWithObject:data];
[machPort sendBeforeDate:[NSDate date] msgid:0 components:components from:nil reserved:0];
}
return 0;
}

View File

@@ -0,0 +1,31 @@
// server.m
#import <Foundation/Foundation.h>
#import <servers/bootstrap.h>
@interface Server : NSObject <NSMachPortDelegate>
@end
@implementation Server
- (void)handlePortMessage:(NSPortMessage *)message {
NSData *data = [[message components] firstObject];
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received: %@", msg);
}
@end
int main() {
@autoreleasepool {
Server *server = [[Server alloc] init];
mach_port_t bp;
task_get_bootstrap_port(mach_task_self(), &bp);
mach_port_t servicePort;
kern_return_t kr = bootstrap_check_in(bp, "com.crimson.message_service", &servicePort);
if (kr != KERN_SUCCESS) return 1;
NSMachPort *port = [[NSMachPort alloc] initWithMachPort:servicePort];
port.delegate = server;
[[NSRunLoop currentRunLoop] addPort:port forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
}
return 0;
}