上一篇完成了簡單的 Server 端,服務端透過 WriteStreamClientCallBack 函式向客戶端送出「你好,客戶端!」。本篇來做客戶端:需要一個 UILabel 顯示收到的訊息,以及兩個按鈕——一個觸發接收、一個送出「收到啦,服務端!」。
#import <UIKit/UIKit.h>
#import <CoreFoundation/CoreFoundation.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8734 // 連接埠可視情況調整
@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
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
// 初始化客戶端網路連線
- (void)initNetworkCommunication
{
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
// 填入伺服器 IP;若不知道可用網路掃描工具查詢
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.103",
PORT, &readStream, &writeStream);
self.inputStream = (__bridge_transfer NSInputStream *)readStream;
self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
}
// 關閉數據流
-(void)close
{
[self.outputStream close];
[self.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream setDelegate:nil];
[self.inputStream close];
[self.inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream setDelegate:nil];
}
// 送出資料
- (IBAction)sendData:(id)sender
{
flag = 0;
[self initNetworkCommunication];
}
// 接收資料
- (IBAction)receiveData:(id)sender
{
flag = 1;
[self initNetworkCommunication];
}
-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
switch (streamEvent) {
case NSStreamEventNone:
break;
case NSStreamEventOpenCompleted: // 成功開啟流
break;
case NSStreamEventHasBytesAvailable: // 有資料可讀
if (flag == 1 && theStream == _inputStream) {
NSMutableData *input = [[NSMutableData alloc] init];
uint8_t buffer[2048];
int len;
while ([self.inputStream hasBytesAvailable]) {
len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
[input appendBytes:buffer length:len];
}
}
NSString *resultstring = [[NSString alloc] initWithData:input
encoding:NSUTF8StringEncoding];
NSLog(@"接收:%@", resultstring);
self.message.text = resultstring;
}
break;
case NSStreamEventHasSpaceAvailable: // 可寫入資料
if (flag == 0 && theStream == _outputStream) {
UInt8 buff[] = "收到啦,服務端!";
[self.outputStream write:buff maxLength:strlen((const char*)buff) + 1];
// 必須關閉輸出流,否則服務端讀取不會停止
[self.outputStream close];
}
break;
case NSStreamEventErrorOccurred: // 發生錯誤
[self close];
break;
case NSStreamEventEndEncountered: // 流結束
NSLog(@"Error:%d:%@", [[theStream streamError] code],
[[theStream streamError] localizedDescription]);
break;
default:
[self close];
break;
}
}
@end

__bridge_transfer 把產權交給 ARC 管理,避免手動 CFRelease 或記憶體洩漏。