BufferedWriterクラスを使用してサーバーにメッセージを送信する
|Socketクラスを使用してソケット通信をするではサーバーへ接続してメッセージを受け取る方法を紹介しましたが、今回はサーバーへメッセージを送信する方法を紹介します。
詳細は以下から。
・BufferedWriterクラス
BufferedWriterクラスは文字型出力ストリームに効率的に文字を書き込む機能をサポートしてくれるクラスです。
以下のようにインスタンス化することでサーバーとの文字型出力ストリームを確立できます。
1 2 | BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( "サーバーと接続が確立しているSocketクラスオブジェクト" .getOutputStream())); |
サーバーとの文字型出力ストリームが確立できたらwriteメソッドでストリームにメッセージを書き出し、flushメソッドでメッセージを送信します。
1 2 | writer.write( "サーバーへ送信するメッセージ" ); writer.flush(); |
・パーミッションの追加
今回もサーバーと通信を行うので、Socketクラスを使用してソケット通信をするを参考にしてパーミッションにandroid.permission.INTERNETを追加して下さい。
・サンプルコード
今回のサンプルコードはSocketクラスを使用してソケット通信をするのコードにメソッドを追加する形で作成しています。
接続先は前回と同様にYahooメールサーバーになるので、サンプルの実行にはYahooメールアカウントが必要になります。
サンプルコードの全内容はこちらからSVNでダウンロード可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | public class SocketWriteSample extends Activity { Socket connection = null ; BufferedReader reader = null ; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button) findViewById(R.id.Button01); btn.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { connect(); login(); } }); } private void connect() { //前回と同内容の為、省略 } private void login() { TextView tv = (TextView) findViewById(R.id.TextView01); // 入力されたIDを取得 EditText id = (EditText) findViewById(R.id.EditText01); CharSequence idStr = id.getText(); // 入力されたパスワードを取得 EditText pass = (EditText) findViewById(R.id.EditText02); CharSequence passStr = pass.getText(); BufferedWriter writer = null ; try { // メッセージ送信オブジェクトのインスタンス化 writer = new BufferedWriter( new OutputStreamWriter( connection.getOutputStream())); // ログインIDの送信 writer.write(idStr.toString() + "\r\n" ); writer.flush(); // ログインIDの正否判定 String message = reader.readLine(); if (!(message.matches( "^\\+OK.*$" ))) { tv.setText( "ID認証:OK\r\n" ); } else { tv.setText( "ログインIDが不正です。" ); return ; } // ログインパスワードの送信 writer.write(passStr.toString() + "\r\n" ); writer.flush(); // ログインパスワードの正否判定 message = reader.readLine(); if (!(message.matches( "^\\+OK.*$" ))) { tv.append( "パスワード認証:OK" ); } else { tv.setText( "パスワードが不正です。" ); return ; } } catch (IOException e) { e.printStackTrace(); tv.setText( "エラー内容:" + e.toString()); Toast.makeText( this , "サーバーとの接続に失敗しました。" , Toast.LENGTH_SHORT).show(); } finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); tv.setText( "エラー内容:" + e.toString()); Toast.makeText( this , "サーバーとの接続に失敗しました。" , Toast.LENGTH_SHORT).show(); } } } } |
30~36行目ではEditTextに入力されたIDとパスワードを文字列として取得しています。
41、42行目ではサーバーとの文字型出力ストリームを確立したBufferedWriterクラスオブジェクトをインスタンス化しています。
45、46行目と58、59行目では、writeメソッドとflushメソッドを使用して、サーバーにメッセージを送信しています。