アプリケーションのテスト
これで必要な部品は用意できました。それらを結合すれば、実際にサーバを使ってコードをテストできます。NetworkViewController.hファイルで、次のアウトレットとアクションを宣言します。
#import
@interface NetworkViewController : UIViewController {
IBOutlet UITextField *txtMessage;
}
@property (nonatomic, retain) UITextField *txtMessage;
-(IBAction) btnSend: (id) sender;
@end
NetworkViewController.xibファイルをダブルクリックしてInterface Builderで編集します。Viewウィンドウに次のビューを配置します(図1を参照)。
- Text Field
- Round Rect Button
以下の操作を行います。
- Controlキーを押しながら[File's Owner]アイテムをクリックし、Text Fieldビューまでドラッグ&ドロップする。[txtMessage]を選択する
- Controlキーを押しながらRound Rect Buttonビューをクリックし、[File's Owner]アイテムまでドラッグ&ドロップする。[btnSend:]を選択する
[File's Owner]アイテムを右クリックして接続を確認します(図2を参照)。
NetworkViewController.mファイルに戻り、以下の行をviewDidLoadメソッドに追加します。
- (void)viewDidLoad {
[self connectToServerUsingStream:@"192.168.1.102" portNo:500];
//---OR---
//[self connectToServerUsingCFStream:@"192.168.1.102" portNo:500];
[super viewDidLoad];
}
上のコードでは、IPアドレスが192.168.1.102(ポート番号500)のサーバに接続するものと仮定しています。サーバコードをどう書くかは、すぐ後で説明します。
btnSend:メソッドを次のように実装します。
-(IBAction) btnSend: (id) sender {
const uint8_t *str =
(uint8_t *) [txtMessage.text cStringUsingEncoding:NSASCIIStringEncoding];
[self writeToServer:str];
txtMessage.text = @"";
}
txtMessageアウトレットをdeallocメソッド内で解放します。
- (void)dealloc {
[txtMessage release];
[self disconnect];
[iStream release];
[oStream release];
if (readStream) CFRelease(readStream);
if (writeStream) CFRelease(writeStream);
[super dealloc];
}
サーバを作成する
以上でiPhone上のクライアントが完成したので、サーバにテキストを送信できます。アプリケーションのテスト用として、ごく簡単なコンソールサーバをC#で作成しました。Program.csファイル(リスト3)を参照ください。
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
namespace Server_CS
{
class Program
{
const int portNo = 500;
static void Main(string[] args)
{
System.Net.IPAddress localAdd =
System.Net.IPAddress.Parse("192.168.1.102");
TcpListener listener = new TcpListener(localAdd, portNo);
listener.Start();
while (true)
{
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
byte[] data = new byte[tcpClient.ReceiveBufferSize];
int numBytesRead = ns.Read(data, 0,
System.Convert.ToInt32(tcpClient.ReceiveBufferSize));
Console.WriteLine("Received :" +
Encoding.ASCII.GetString(data, 0, numBytesRead));
//---write back to the client---
ns.Write(data, 0, numBytesRead);
}
}
}
}
このサーバプログラムは以下の処理を行います。
- サーバのIPアドレスを192.168.1.102と仮定する。実際のテストでは、このサーバアプリケーションを実行するコンピュータのIPアドレスに書き換える必要がある。
- 受け取ったデータをそのままクライアントへ送り返す。
- いったんデータを受け取ると、もうデータをリッスンしなくなる。クライアントから再びデータを送信するためには、サーバとの接続を再度確立する必要がある。
サーバコードが用意できたらiPhoneアプリをテストできます。Text Fieldビューにテキストを入力し、[Send]ボタンをクリックします。接続が確立されれば、Alert Viewに受信データが表示されます。


![図2 確認:[File's Owner]アイテムで接続を確認する](http://cz-cdn.shoeisha.jp/static/images/article/4936/2s.gif)