@ViewController.h
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 9000
@interface ViewController : UIViewController<NSStreamDelegate>
{
int flag ; //動作標志 0為傳送 1為接收
}
@property (nonatomic, retain) NSInputStream *inputStream;
@property (nonatomic, retain) NSOutputStream *outputStream;
@property (weak, nonatomic) IBOutlet UILabel *message;
- (IBAction)sendData:(id)sender;
- (IBAction)receiveData:(id)sender;
@end
define input & output stream
- (void)initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.100", PORT, &readStream, &writeStream);
_inputStream = (__bridge_transfer NSInputStream *)readStream;
_outputStream = (__bridge_transfer NSOutputStream
*)writeStream;
[_inputStream setDelegate:self];
[_outputStream setDelegate:self];
[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
}
initialize Network, set ip address & port number
-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSString *event;
switch (streamEvent) {
case NSStreamEventNone:
event = @"NSStreamEventNone";
break;
case NSStreamEventOpenCompleted:
event = @"NSStreamEventOpenCompleted";
break;
case NSStreamEventHasBytesAvailable:
event = @"NSStreamEventHasBytesAvailable";
if (flag ==1 && theStream == _inputStream) {
NSMutableData *input = [[NSMutableData alloc] init];
uint8_t buffer[1024];
int len;
while([_inputStream hasBytesAvailable])
{
len = [_inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
[input appendBytes:buffer length:len];
}
}
NSString *resultstring = [[NSString alloc] initWithData:input encoding:NSUTF8StringEncoding];
NSLog(@"接收:%@",resultstring);
_message.text = resultstring;
}
break;
case NSStreamEventHasSpaceAvailable:
event = @"NSStreamEventHasSpaceAvailable";
if (flag ==0 && theStream == _outputStream) {
//輸出
UInt8 buff[] = "Hello Server!";
[_outputStream write:buff maxLength: strlen((const char*)buff)+1];
//必須關閉輸出流否則,伺服器端一直讀取不會停止,
[_outputStream close];
}
break;
case NSStreamEventErrorOccurred:
event = @"NSStreamEventErrorOccurred";
[self close];
break;
case NSStreamEventEndEncountered:
event = @"NSStreamEventEndEncountered";
NSLog(@"Error:%d:%@",[[theStream streamError] code], [[theStream streamError] localizedDescription]);
break;
default:
[self close];
event = @"Unknown";
break;
}
NSLog(@"event------%@",event);
}
當有stream時,會呼叫此函數
沒有留言:
張貼留言