LeoNatan / LNSocketConnection

A simple socket connection framework for two–way peer–to–peer communication.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LNSocketConnection

A simple socket connection framework for two–way peer–to–peer communication.

The framework is intended to be used in conjunction with NSNetService and NSNetServiceBrowser to create communication between two peers.

Using

Add LNSocketConnection.xcodeproj to your project. In your target's settings, add LNSocketConnection.framework to embedded binaries.

Import the framework's umbrella header:

#import <LNSocketConnection/LNSocketConnection.h>

Opening Connection

Server
- (void)netService:(NSNetService *)sender didAcceptConnectionWithInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream
{
	_socketConnection = [[LNSocketConnection alloc] initWithInputStream:inputStream outputStream:outputStream queue:_socketQueue];
	_socketConnection.delegate = self;
	[_socketConnection open];
}
Client
- (void)netServiceDidResolveAddress:(NSNetService *)sender
{
	_socketConnection = [[LNSocketConnection alloc] initWithHostName:sender.hostName port:sender.port queue:_socketQueue];
	_socketConnection.delegate = self;
	[_socketConnection open];
}

Reading Data

[_socketConnection readDataWithCompletionHandler:^(NSData * _Nullable data, NSError * _Nullable error) {
	if(error)
	{
		NSLog(@"Read error: %@", error);
		return;
	}
		
	NSLog(@"Read data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];

Writing Data

NSString* str = [NSString stringWithFormat:@"The time is: %@", [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]];
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
[_socketConnection writeData:data completionHandler:^(NSError * _Nullable error) {	
	if(error)
	{
		NSLog(@"Write error: %@", error);
		return;
	}
	
	NSLog(@"Successfully wrote data");
}];

Acknowledgements

Originally developed by me for Wix.

About

A simple socket connection framework for two–way peer–to–peer communication.

License:MIT License


Languages

Language:Objective-C 100.0%