SlideShare a Scribd company logo
1 of 16
Download to read offline
2013

[PS11]ネットワーク
第 4 回目
HTTP 通信/ソケット通信
1.

Socket 通信を行うプログラム
ソケット通信を利用したチャットクライアント(Android アプリ)とサーバプログラム
を作成します。今回は、サーバは自分の PC 内に起動させます。

※Android Virtual Device(AVD)の設定
Eclipse からエミュレータでデバッグを行うために、エミュレータの端末の設定を追加しま
す。
Eclipse のメニューから[ウインドウ]->[AVD Manager]を選択し、[New]ボタンをクリック。
以下のように設定してください。

ソースコード(クライアント側)
Eclipse を開いて、パッケージエクスプローラーで右クリックし、[新規]->[Android プ
ロジェクト]を選択します。
プロジェクト名は
「SocketEx」
としてください。
Target SDK
と Compile With は Android4.0(IceCreamSandwich)を選びます。ActivityName は
「SocketEx」としましょう。
package com.example.socketex;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class SocketEx extends Activity implements View.OnClickListener{
private final static String BR = System.getProperty("line.separator");
private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private final static int MP = LinearLayout.LayoutParams.MATCH_PARENT;
private static final String ADDRESS = "192.168.1.100"; ※変更すること!
private TextView lblReceive;
private EditText editText;
private Button btnSend;
private Socket socket;
private InputStream in;
private OutputStream out;
private boolean error;
private final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
LinearLayout layout = new LinearLayout(this);
layout.setBackgroundColor(Color.rgb(255,255,255));
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
editText = new EditText(this);
editText.setId(2);
editText.setText("", TextView.BufferType.NORMAL);
editText.setLayoutParams(new

LinearLayout.LayoutParams(MP,

WC));
layout.addView(editText);
btnSend = new Button(this);
btnSend.setText("送信");
btnSend.setOnClickListener(this);
btnSend.setLayoutParams(new

LinearLayout.LayoutParams(WC,

WC));
layout.addView(btnSend);
lblReceive = new TextView(this);
lblReceive.setId(1);
lblReceive.setText("");
lblReceive.setTextSize(16.0f);
lblReceive.setTextColor(Color.rgb(0, 0, 0));
lblReceive.setLayoutParams(new
WC));
layout.addView(lblReceive);

LinearLayout.LayoutParams(MP,
}
@Override
public void onStart() {
super.onStart();
Thread thread = new Thread() {
public void run() {
try {
connect(ADDRESS, 8080);
} catch (Exception e) {
}
}
};
thread.start();
}
@Override
public void onStop() {
super.onStop();
disconnect();
}
private void addText(final String text) {
handler.post(new Runnable() {
@Override
public void run() {
lblReceive.setText(text + BR + lblReceive.getText());
}
});
}
private void connect(String address, int port) {
int size;
String str;
byte[] w = new byte[1024];
try {
addText("接続中");
socket = new Socket(address, port);
in = socket.getInputStream();
out = socket.getOutputStream();
addText("接続完了");
while(socket != null && socket.isConnected()) {
size = in.read(w);
if (size <= 0) {
continue;
}
str = new String(w, 0, size, "UTF-8");
addText(str);
}
} catch (Exception e) {
addText("通信に失敗しました。");
}
}
private void disconnect() {
try {
socket.close();
socket = null;
} catch (Exception e) {
}
}
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
error = false;
try {
if (socket != null && socket.isConnected()) {
byte[]

w

=

editText.getText().toString().getBytes("UTF8");
out.write(w);
out.flush();
}
} catch (Exception e) {
error = true;
}
handler.post(new Runnable() {
public void run() {
if (error) {
addText(" 通 信 に 失 敗 し ま
した");
} else {
editText.setText("",
TextView.BufferType.NORMAL);
}
}
});
}
});
thread.start();
}
}
ソースコード(サーバ側)
Eclipse で新規 Java プロジェクト『chatserver』を作成します。作成したら、src フォルダ
の直下に、
『ChatServer.java』
『CharServerThread.java』2 つの java ファイルを作成しま
す。ソースコードはそれぞれ以下のように記述します。
○ChatServer.java
package com.example;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* This class launches the web application in an embedded Jetty container.
* This is the entry point to your application. The Java command that is used for
* launching should fire this main method.
*
*/
public class ChatServer {
public void start(int port) {
ServerSocket server;
Socket socket;
ChatServerThread thread;
try {
server = new ServerSocket(port);
System.err.println("ChatServer start" +
"¥nIP

Address:"

InetAddress.getLocalHost().getHostAddress()
+ "¥nPort:" + port);
while (true) {
try {
socket = server.accept();
thread = new ChatServerThread(socket);
thread.start();
} catch (IOException e) {
System.out.println(e);
}

+
}
} catch (IOException e) {
System.err.println(e);
}
}
public static void main(String[] args) throws Exception{
ChatServer server = new ChatServer();
server.start(8080);
}
}
○ChatServerThread.java
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServerThread extends Thread {
private

static

List<ChatServerThread>

ArrayList<ChatServerThread>();
private Socket socket;
public ChatServerThread(Socket socket) {
super();
this.socket = socket;
threads.add(this);
}

threads

=

new
public void run() {
InputStream in = null;
String message;
int size;
byte[] w = new byte[10240];
try {
System.err.println("ChatServerThread start");
in = socket.getInputStream();
while(true) {
try {
size = in.read(w);
if (size <= 0) {
throw new IOException();
}
message = new String(w, 0, size, "UTF8");
System.out.println(message);
sendMessageAll(message);
} catch(IOException e) {
System.out.println("ChatServerThread
stop");
socket.close();
threads.remove(this);
return;
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public void sendMessageAll(String message) {
for (ChatServerThread thread : threads) {
if (thread.isAlive()) {
thread.sendMessage(this, message);
}
}
System.out.println(message);
}
public void sendMessage(ChatServerThread talker, String message) {
try {
OutputStream out = socket.getOutputStream();
byte[] w = message.getBytes("UTF8");
out.write(w);
out.flush();
} catch (IOException e) {
}
}
}
ソースを記述したら、Java アプリケーションとして実行してください。
その後、Android アプリを起動します。
2.

HTTP 通信を行う Android アプリ

HTTP 通信の GET/POST メソッドを行ってネット上の情報を表示するアプリを作成します。
ソースコード
Eclipse を開いて、パッケージエクスプローラーで右クリックし、[新規]->[Android プロジ
ェクト]を選択します。
プロジェクト名は
「HttpEx」
としてください。
Target SDK と Compile
With は Android4.0(IceCreamSandwich)を選びます。ActivityName は「HttpEx」としま
しょう。
プロジェクトが作成出来たら、src.com.example.httpex フォルダの HttpEx.java ファイル
を以下のように編集してください。
また、AndroidManifest.xml を開き、
『Permission』タブの中の Add ボタンをクリックし
て、
『User Permission』を選択します。Name は『android.permission.INTERNET』を選
択してください。
package com.example.httpex;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class HttpEx extends Activity implements View.OnClickListener{
private static final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private static final int MP = LinearLayout.LayoutParams.MATCH_PARENT;
private EditText editText;
// リクエスト先の URL
private static final String URL = "http://httpserverex.herokuapp.com/hello";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// レイアウトの生成
LinearLayout layout = new LinearLayout(this);
layout.setBackgroundColor(Color.rgb(255, 255, 255));
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// エディットテキストの生成
editText = new EditText(this);
editText.setText("", EditText.BufferType.NORMAL);
editText.setLayoutParams(new

LinearLayout.LayoutParams(MP,

WC));
layout.addView(editText);
layout.addView(makeButton("HTTP 通信", "read"));
}
/**
* ボタンの生成
* @param text
* @param tag
* @return
*/
private Button makeButton(String text, String tag) {
Button button = new Button(this);
button.setText(text);
button.setTag(tag);
button.setOnClickListener(this);
button.setLayoutParams(new

LinearLayout.LayoutParams(WC,

WC));
return button;
}
@Override
public void onClick(View arg0) {
String tag = (String) arg0.getTag();
if (tag.equals("read")) {
Thread thread = new Thread(new Runnable() {
String text = null;
@Override
public void run() {
// HTTP 通信
try {
text

=

String(httpToData(URL));
} catch (Exception e) {
text = null;
}
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
if (text != null) {
editText.setText(text, TextView.BufferType.EDITABLE);
} else {
HttpEx.showDialog(HttpEx.this, "エラー", "読み込みに失敗しました");
}
}
});
}
});
thread.start();
}
}
public static byte[] httpToData(String path) throws Exception {
byte[] write = new byte[1024];
HttpURLConnection connection = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
// HTTP 接続のオープン

new
URL url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
in = connection.getInputStream();
out = new ByteArrayOutputStream();
int size;
while ((size = in.read(write)) > 0) {
out.write(write, 0, size);
}
out.close();
in.close();
connection.disconnect();
return out.toByteArray();
} catch (Exception e) {
try {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception e2) {
}
throw e;
}
}
private static void showDialog(Context context, String title, String text) {
AlertDialog.Builder ad = new AlertDialog.Builder(context);
ad.setTitle(title);
ad.setMessage(text);
ad.setPositiveButton("OK", null);
ad.show();
}
}
ソースが記述出来たら、Android Application として実行してください。
<演習>
GET リクエストで上記の URL にアクセスしていますが、POST 用のボタンを追加し、そ
のボタンをクリックされた場合は、POST リクエストを行うように修正しなさい。
また、リクエストクエリも追加で送信出来るように修正しなさい。

More Related Content

What's hot

Google App Engine for Java
Google App Engine for JavaGoogle App Engine for Java
Google App Engine for Java
Takuya Tsuchida
 
node+socket.io+enchant.jsでチャットゲーを作る
node+socket.io+enchant.jsでチャットゲーを作るnode+socket.io+enchant.jsでチャットゲーを作る
node+socket.io+enchant.jsでチャットゲーを作る
Kiyoshi SATOH
 

What's hot (20)

PHP 2大 web フレームワークの徹底比較!
PHP 2大 web フレームワークの徹底比較!PHP 2大 web フレームワークの徹底比較!
PHP 2大 web フレームワークの徹底比較!
 
Team Foundation Server プロセステンプレートの変更 手順書
Team Foundation Server プロセステンプレートの変更 手順書Team Foundation Server プロセステンプレートの変更 手順書
Team Foundation Server プロセステンプレートの変更 手順書
 
「Entity Framework Coreを使ってみる」 公開用
「Entity Framework Coreを使ってみる」 公開用「Entity Framework Coreを使ってみる」 公開用
「Entity Framework Coreを使ってみる」 公開用
 
Team Foundation Server 2015 による テスト工数削減
Team Foundation Server 2015 によるテスト工数削減Team Foundation Server 2015 によるテスト工数削減
Team Foundation Server 2015 による テスト工数削減
 
もう怖くない! Team Foundation Server 2015 Update 1 ワークアイテム管理と テンプレートのカスタマイズ 概要
もう怖くない!Team Foundation Server 2015 Update 1 ワークアイテム管理とテンプレートのカスタマイズ 概要もう怖くない!Team Foundation Server 2015 Update 1 ワークアイテム管理とテンプレートのカスタマイズ 概要
もう怖くない! Team Foundation Server 2015 Update 1 ワークアイテム管理と テンプレートのカスタマイズ 概要
 
Visual Studio Code 拡張の勘所
Visual Studio Code 拡張の勘所Visual Studio Code 拡張の勘所
Visual Studio Code 拡張の勘所
 
Team Foundation Server 2015 Update 3 インストール 手順書 ~ SQL Server インストールから チームプロジェ...
Team Foundation Server 2015 Update 3インストール 手順書~ SQL Server インストールから チームプロジェ...Team Foundation Server 2015 Update 3インストール 手順書~ SQL Server インストールから チームプロジェ...
Team Foundation Server 2015 Update 3 インストール 手順書 ~ SQL Server インストールから チームプロジェ...
 
Hokuriku.NET ASP.NET MVC入門 「実践」 20120825
Hokuriku.NET ASP.NET MVC入門 「実践」 20120825 Hokuriku.NET ASP.NET MVC入門 「実践」 20120825
Hokuriku.NET ASP.NET MVC入門 「実践」 20120825
 
Spring と TDD
Spring と TDDSpring と TDD
Spring と TDD
 
CLRH_120414_WFTDD
CLRH_120414_WFTDDCLRH_120414_WFTDD
CLRH_120414_WFTDD
 
Selenium webdriver使ってみようず
Selenium webdriver使ってみようずSelenium webdriver使ってみようず
Selenium webdriver使ってみようず
 
Team Foundation Server 2015 Update 3 アップグレード 手順書 ~ Team Foundation Server 201...
Team Foundation Server 2015 Update 3アップグレード 手順書~ Team Foundation Server 201...Team Foundation Server 2015 Update 3アップグレード 手順書~ Team Foundation Server 201...
Team Foundation Server 2015 Update 3 アップグレード 手順書 ~ Team Foundation Server 201...
 
ゲンバのSwift
ゲンバのSwiftゲンバのSwift
ゲンバのSwift
 
JavaScriptでWebDriverのテストコードを書きましょ
JavaScriptでWebDriverのテストコードを書きましょJavaScriptでWebDriverのテストコードを書きましょ
JavaScriptでWebDriverのテストコードを書きましょ
 
Google App Engine for Java
Google App Engine for JavaGoogle App Engine for Java
Google App Engine for Java
 
Eclipse ADTとAndroidStudio両方で動かせる開発環境構築
Eclipse ADTとAndroidStudio両方で動かせる開発環境構築Eclipse ADTとAndroidStudio両方で動かせる開発環境構築
Eclipse ADTとAndroidStudio両方で動かせる開発環境構築
 
node+socket.io+enchant.jsでチャットゲーを作る
node+socket.io+enchant.jsでチャットゲーを作るnode+socket.io+enchant.jsでチャットゲーを作る
node+socket.io+enchant.jsでチャットゲーを作る
 
Apexデザインパターン
ApexデザインパターンApexデザインパターン
Apexデザインパターン
 
Team Foundation Server 2015 Update 2.1 アップグレード 手順書 ~ Team Foundation Server 2...
Team Foundation Server 2015 Update 2.1アップグレード 手順書~ Team Foundation Server 2...Team Foundation Server 2015 Update 2.1アップグレード 手順書~ Team Foundation Server 2...
Team Foundation Server 2015 Update 2.1 アップグレード 手順書 ~ Team Foundation Server 2...
 
Selenium webdriver使ってみようず
Selenium webdriver使ってみようずSelenium webdriver使ってみようず
Selenium webdriver使ってみようず
 

Viewers also liked

Introduction session 1 - Vietnam
Introduction session 1 - VietnamIntroduction session 1 - Vietnam
Introduction session 1 - Vietnam
Kulachart Ruamchart
 
Making Strides for Dayton Breast Cancer Walk
Making Strides for Dayton Breast Cancer WalkMaking Strides for Dayton Breast Cancer Walk
Making Strides for Dayton Breast Cancer Walk
April Swett
 
Introduction session 1 - Thailand
Introduction session 1 - ThailandIntroduction session 1 - Thailand
Introduction session 1 - Thailand
Kulachart Ruamchart
 
Introduction session 1 - Cambodia
Introduction session 1 - CambodiaIntroduction session 1 - Cambodia
Introduction session 1 - Cambodia
Kulachart Ruamchart
 
Introduction session 1 - Myanmar
Introduction session 1 - MyanmarIntroduction session 1 - Myanmar
Introduction session 1 - Myanmar
Kulachart Ruamchart
 

Viewers also liked (7)

My BMI is Not The Issue, But I Have A Condition
My BMI is Not The Issue, But I Have A ConditionMy BMI is Not The Issue, But I Have A Condition
My BMI is Not The Issue, But I Have A Condition
 
Introduction session 1 - Vietnam
Introduction session 1 - VietnamIntroduction session 1 - Vietnam
Introduction session 1 - Vietnam
 
Making Strides for Dayton Breast Cancer Walk
Making Strides for Dayton Breast Cancer WalkMaking Strides for Dayton Breast Cancer Walk
Making Strides for Dayton Breast Cancer Walk
 
You Are Never Too Old For a Mentor
You Are Never Too Old For a MentorYou Are Never Too Old For a Mentor
You Are Never Too Old For a Mentor
 
Introduction session 1 - Thailand
Introduction session 1 - ThailandIntroduction session 1 - Thailand
Introduction session 1 - Thailand
 
Introduction session 1 - Cambodia
Introduction session 1 - CambodiaIntroduction session 1 - Cambodia
Introduction session 1 - Cambodia
 
Introduction session 1 - Myanmar
Introduction session 1 - MyanmarIntroduction session 1 - Myanmar
Introduction session 1 - Myanmar
 

Similar to [Ps11]ネットワーク第4回

13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejs13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejs
Takayoshi Tanaka
 
Titanium Mobile
Titanium MobileTitanium Mobile
Titanium Mobile
Naoya Ito
 
Web1.0のハイブリッドアプリ開発
Web1.0のハイブリッドアプリ開発Web1.0のハイブリッドアプリ開発
Web1.0のハイブリッドアプリ開発
Kenta Tsuji
 
Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)
Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)
Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)
JPCERT Coordination Center
 
Pro aspnetmvc3framework chap19
Pro aspnetmvc3framework chap19Pro aspnetmvc3framework chap19
Pro aspnetmvc3framework chap19
Hideki Hashizume
 
SpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsug
SpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsugSpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsug
SpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsug
Y Watanabe
 
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考えるNetラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
david9142
 

Similar to [Ps11]ネットワーク第4回 (20)

Eclipse と Liberty プロファイルで始める Java EE 開発ハンズオン #jjug_ccc #ccc_r51
Eclipse と Liberty プロファイルで始める Java EE 開発ハンズオン #jjug_ccc #ccc_r51Eclipse と Liberty プロファイルで始める Java EE 開発ハンズオン #jjug_ccc #ccc_r51
Eclipse と Liberty プロファイルで始める Java EE 開発ハンズオン #jjug_ccc #ccc_r51
 
13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejs13016 n分で作るtype scriptでnodejs
13016 n分で作るtype scriptでnodejs
 
C#版人狼知能エージェントの作り方~Visual Studio編~(AIWolf.NET 1.0.6版)
C#版人狼知能エージェントの作り方~Visual Studio編~(AIWolf.NET 1.0.6版)C#版人狼知能エージェントの作り方~Visual Studio編~(AIWolf.NET 1.0.6版)
C#版人狼知能エージェントの作り方~Visual Studio編~(AIWolf.NET 1.0.6版)
 
jQuery と MVC で実践する標準志向 Web 開発
jQuery と MVC で実践する標準志向 Web 開発jQuery と MVC で実践する標準志向 Web 開発
jQuery と MVC で実践する標準志向 Web 開発
 
cocos2d-xとネイティブ間の連携
cocos2d-xとネイティブ間の連携cocos2d-xとネイティブ間の連携
cocos2d-xとネイティブ間の連携
 
Titanium Mobile
Titanium MobileTitanium Mobile
Titanium Mobile
 
How to Make Own Framework built on OWIN
How to Make Own Framework built on OWINHow to Make Own Framework built on OWIN
How to Make Own Framework built on OWIN
 
CEDEC 2013 Unity on Windows 8
CEDEC 2013 Unity on Windows 8CEDEC 2013 Unity on Windows 8
CEDEC 2013 Unity on Windows 8
 
Web1.0のハイブリッドアプリ開発
Web1.0のハイブリッドアプリ開発Web1.0のハイブリッドアプリ開発
Web1.0のハイブリッドアプリ開発
 
Cocos2d xをさらにさわってみよう!
Cocos2d xをさらにさわってみよう!Cocos2d xをさらにさわってみよう!
Cocos2d xをさらにさわってみよう!
 
.NET CoreとVS Codeで作る人狼知能
.NET CoreとVS Codeで作る人狼知能.NET CoreとVS Codeで作る人狼知能
.NET CoreとVS Codeで作る人狼知能
 
Ajax basic
Ajax basicAjax basic
Ajax basic
 
Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)
Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)
Apache CommonsのHttpClientに おけるSSLサーバ証明書検証不備 (CVE-2012-5783)
 
sveltekit-ja.pdf
sveltekit-ja.pdfsveltekit-ja.pdf
sveltekit-ja.pdf
 
Hbstudy41 auto scaling
Hbstudy41 auto scalingHbstudy41 auto scaling
Hbstudy41 auto scaling
 
Pro aspnetmvc3framework chap19
Pro aspnetmvc3framework chap19Pro aspnetmvc3framework chap19
Pro aspnetmvc3framework chap19
 
Android Studioの魅力
Android Studioの魅力Android Studioの魅力
Android Studioの魅力
 
SpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsug
SpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsugSpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsug
SpringMVCとmixer2で作るWebアプリのキホン 2013-01-24 Spring勉強会 #jsug
 
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考えるNetラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
 
Next2Dで始めるゲーム開発 - Game Development Starting with Next2D
Next2Dで始めるゲーム開発  - Game Development Starting with Next2DNext2Dで始めるゲーム開発  - Game Development Starting with Next2D
Next2Dで始めるゲーム開発 - Game Development Starting with Next2D
 

More from Yukiko Kato

Javaデザインパターン入門【第2回】
Javaデザインパターン入門【第2回】Javaデザインパターン入門【第2回】
Javaデザインパターン入門【第2回】
Yukiko Kato
 
Javaプログラミング入門【第8回】
Javaプログラミング入門【第8回】Javaプログラミング入門【第8回】
Javaプログラミング入門【第8回】
Yukiko Kato
 
Javaプログラミング入門【第6回】
Javaプログラミング入門【第6回】Javaプログラミング入門【第6回】
Javaプログラミング入門【第6回】
Yukiko Kato
 
HTTPとは(HerokuとADTで実践編)
HTTPとは(HerokuとADTで実践編)HTTPとは(HerokuとADTで実践編)
HTTPとは(HerokuとADTで実践編)
Yukiko Kato
 

More from Yukiko Kato (20)

Javaデザインパターン入門【第3回】
Javaデザインパターン入門【第3回】Javaデザインパターン入門【第3回】
Javaデザインパターン入門【第3回】
 
Javaデザインパターン入門【第2回】
Javaデザインパターン入門【第2回】Javaデザインパターン入門【第2回】
Javaデザインパターン入門【第2回】
 
Javaプログラミング入門【第9回】
Javaプログラミング入門【第9回】Javaプログラミング入門【第9回】
Javaプログラミング入門【第9回】
 
ネットワーク第9回
ネットワーク第9回ネットワーク第9回
ネットワーク第9回
 
Javaプログラミング入門【第8回】
Javaプログラミング入門【第8回】Javaプログラミング入門【第8回】
Javaプログラミング入門【第8回】
 
ネットワーク第8回目
ネットワーク第8回目ネットワーク第8回目
ネットワーク第8回目
 
Javaプログラミング入門【第7回】
Javaプログラミング入門【第7回】Javaプログラミング入門【第7回】
Javaプログラミング入門【第7回】
 
ネットワーク第7回
ネットワーク第7回ネットワーク第7回
ネットワーク第7回
 
[PS11]ネットワーク第6回
[PS11]ネットワーク第6回[PS11]ネットワーク第6回
[PS11]ネットワーク第6回
 
Javaプログラミング入門【第6回】
Javaプログラミング入門【第6回】Javaプログラミング入門【第6回】
Javaプログラミング入門【第6回】
 
ネットワーク第6回
ネットワーク第6回ネットワーク第6回
ネットワーク第6回
 
[PS11]ネットワーク第5回
[PS11]ネットワーク第5回[PS11]ネットワーク第5回
[PS11]ネットワーク第5回
 
Javaプログラミング入門【第5回】
Javaプログラミング入門【第5回】Javaプログラミング入門【第5回】
Javaプログラミング入門【第5回】
 
Javaプログラミング入門【第4回】
Javaプログラミング入門【第4回】Javaプログラミング入門【第4回】
Javaプログラミング入門【第4回】
 
ネットワーク第4回目
ネットワーク第4回目ネットワーク第4回目
ネットワーク第4回目
 
Javaプログラミング入門【第3回】
Javaプログラミング入門【第3回】Javaプログラミング入門【第3回】
Javaプログラミング入門【第3回】
 
ネットワーク第3回目
ネットワーク第3回目ネットワーク第3回目
ネットワーク第3回目
 
Javaプログラミング入門【第2回】
Javaプログラミング入門【第2回】Javaプログラミング入門【第2回】
Javaプログラミング入門【第2回】
 
HTTPとは(HerokuとADTで実践編)
HTTPとは(HerokuとADTで実践編)HTTPとは(HerokuとADTで実践編)
HTTPとは(HerokuとADTで実践編)
 
Javaプログラミング入門【第1回】
Javaプログラミング入門【第1回】Javaプログラミング入門【第1回】
Javaプログラミング入門【第1回】
 

Recently uploaded

研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計
研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計
研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計
atsushi061452
 

Recently uploaded (16)

MPAなWebフレームワーク、Astroの紹介 (その1) 2024/05/17の勉強会で発表されたものです。
MPAなWebフレームワーク、Astroの紹介 (その1) 2024/05/17の勉強会で発表されたものです。MPAなWebフレームワーク、Astroの紹介 (その1) 2024/05/17の勉強会で発表されたものです。
MPAなWebフレームワーク、Astroの紹介 (その1) 2024/05/17の勉強会で発表されたものです。
 
研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計
研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計
研究紹介スライド: オフライン強化学習に基づくロボティックスワームの制御器の設計
 
情報を表現するときのポイント
情報を表現するときのポイント情報を表現するときのポイント
情報を表現するときのポイント
 
LoRaWAN無位置ロープ型水漏れセンサー WL03A-LB/LSカタログ ファイル
LoRaWAN無位置ロープ型水漏れセンサー WL03A-LB/LSカタログ ファイルLoRaWAN無位置ロープ型水漏れセンサー WL03A-LB/LSカタログ ファイル
LoRaWAN無位置ロープ型水漏れセンサー WL03A-LB/LSカタログ ファイル
 
ネットワーク可視化 振る舞い検知(NDR)ご紹介_キンドリル202405.pdf
ネットワーク可視化 振る舞い検知(NDR)ご紹介_キンドリル202405.pdfネットワーク可視化 振る舞い検知(NDR)ご紹介_キンドリル202405.pdf
ネットワーク可視化 振る舞い検知(NDR)ご紹介_キンドリル202405.pdf
 
Amazon Cognitoで実装するパスキー (Security-JAWS【第33回】 勉強会)
Amazon Cognitoで実装するパスキー (Security-JAWS【第33回】 勉強会)Amazon Cognitoで実装するパスキー (Security-JAWS【第33回】 勉強会)
Amazon Cognitoで実装するパスキー (Security-JAWS【第33回】 勉強会)
 
20240523_IoTLT_vol111_kitazaki_v1___.pdf
20240523_IoTLT_vol111_kitazaki_v1___.pdf20240523_IoTLT_vol111_kitazaki_v1___.pdf
20240523_IoTLT_vol111_kitazaki_v1___.pdf
 
部内勉強会(IT用語ざっくり学習) 実施日:2024年5月17日(金) 対象者:営業部社員
部内勉強会(IT用語ざっくり学習) 実施日:2024年5月17日(金) 対象者:営業部社員部内勉強会(IT用語ざっくり学習) 実施日:2024年5月17日(金) 対象者:営業部社員
部内勉強会(IT用語ざっくり学習) 実施日:2024年5月17日(金) 対象者:営業部社員
 
Hyperledger Fabricコミュニティ活動体験& Hyperledger Fabric最新状況ご紹介
Hyperledger Fabricコミュニティ活動体験& Hyperledger Fabric最新状況ご紹介Hyperledger Fabricコミュニティ活動体験& Hyperledger Fabric最新状況ご紹介
Hyperledger Fabricコミュニティ活動体験& Hyperledger Fabric最新状況ご紹介
 
5/22 第23回 Customer系エンジニア座談会のスライド 公開用 西口瑛一
5/22 第23回 Customer系エンジニア座談会のスライド 公開用 西口瑛一5/22 第23回 Customer系エンジニア座談会のスライド 公開用 西口瑛一
5/22 第23回 Customer系エンジニア座談会のスライド 公開用 西口瑛一
 
Keywordmap overview material/CINC.co.ltd
Keywordmap overview material/CINC.co.ltdKeywordmap overview material/CINC.co.ltd
Keywordmap overview material/CINC.co.ltd
 
Intranet Development v1.0 (TSG LIVE! 12 LT )
Intranet Development v1.0 (TSG LIVE! 12 LT )Intranet Development v1.0 (TSG LIVE! 12 LT )
Intranet Development v1.0 (TSG LIVE! 12 LT )
 
2024年5月17日 先駆的科学計算フォーラム2024 機械学習を用いた新たなゲーム体験の創出の応用
2024年5月17日 先駆的科学計算フォーラム2024 機械学習を用いた新たなゲーム体験の創出の応用2024年5月17日 先駆的科学計算フォーラム2024 機械学習を用いた新たなゲーム体験の創出の応用
2024年5月17日 先駆的科学計算フォーラム2024 機械学習を用いた新たなゲーム体験の創出の応用
 
ロボットマニピュレーションの作業・動作計画 / rosjp_planning_for_robotic_manipulation_20240521
ロボットマニピュレーションの作業・動作計画 / rosjp_planning_for_robotic_manipulation_20240521ロボットマニピュレーションの作業・動作計画 / rosjp_planning_for_robotic_manipulation_20240521
ロボットマニピュレーションの作業・動作計画 / rosjp_planning_for_robotic_manipulation_20240521
 
クラウド時代におけるSREとUPWARDの取組ーUPWARD株式会社 CTO門畑
クラウド時代におけるSREとUPWARDの取組ーUPWARD株式会社 CTO門畑クラウド時代におけるSREとUPWARDの取組ーUPWARD株式会社 CTO門畑
クラウド時代におけるSREとUPWARDの取組ーUPWARD株式会社 CTO門畑
 
論文紹介:ViTPose: Simple Vision Transformer Baselines for Human Pose Estimation
論文紹介:ViTPose: Simple Vision Transformer Baselines for Human Pose Estimation論文紹介:ViTPose: Simple Vision Transformer Baselines for Human Pose Estimation
論文紹介:ViTPose: Simple Vision Transformer Baselines for Human Pose Estimation
 

[Ps11]ネットワーク第4回

  • 2. 1. Socket 通信を行うプログラム ソケット通信を利用したチャットクライアント(Android アプリ)とサーバプログラム を作成します。今回は、サーバは自分の PC 内に起動させます。 ※Android Virtual Device(AVD)の設定 Eclipse からエミュレータでデバッグを行うために、エミュレータの端末の設定を追加しま す。 Eclipse のメニューから[ウインドウ]->[AVD Manager]を選択し、[New]ボタンをクリック。 以下のように設定してください。 ソースコード(クライアント側) Eclipse を開いて、パッケージエクスプローラーで右クリックし、[新規]->[Android プ
  • 3. ロジェクト]を選択します。 プロジェクト名は 「SocketEx」 としてください。 Target SDK と Compile With は Android4.0(IceCreamSandwich)を選びます。ActivityName は 「SocketEx」としましょう。 package com.example.socketex; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class SocketEx extends Activity implements View.OnClickListener{ private final static String BR = System.getProperty("line.separator"); private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT; private final static int MP = LinearLayout.LayoutParams.MATCH_PARENT; private static final String ADDRESS = "192.168.1.100"; ※変更すること! private TextView lblReceive; private EditText editText; private Button btnSend; private Socket socket; private InputStream in; private OutputStream out; private boolean error;
  • 4. private final Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); LinearLayout layout = new LinearLayout(this); layout.setBackgroundColor(Color.rgb(255,255,255)); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); editText = new EditText(this); editText.setId(2); editText.setText("", TextView.BufferType.NORMAL); editText.setLayoutParams(new LinearLayout.LayoutParams(MP, WC)); layout.addView(editText); btnSend = new Button(this); btnSend.setText("送信"); btnSend.setOnClickListener(this); btnSend.setLayoutParams(new LinearLayout.LayoutParams(WC, WC)); layout.addView(btnSend); lblReceive = new TextView(this); lblReceive.setId(1); lblReceive.setText(""); lblReceive.setTextSize(16.0f); lblReceive.setTextColor(Color.rgb(0, 0, 0)); lblReceive.setLayoutParams(new WC)); layout.addView(lblReceive); LinearLayout.LayoutParams(MP,
  • 5. } @Override public void onStart() { super.onStart(); Thread thread = new Thread() { public void run() { try { connect(ADDRESS, 8080); } catch (Exception e) { } } }; thread.start(); } @Override public void onStop() { super.onStop(); disconnect(); } private void addText(final String text) { handler.post(new Runnable() { @Override public void run() { lblReceive.setText(text + BR + lblReceive.getText()); } }); } private void connect(String address, int port) { int size; String str;
  • 6. byte[] w = new byte[1024]; try { addText("接続中"); socket = new Socket(address, port); in = socket.getInputStream(); out = socket.getOutputStream(); addText("接続完了"); while(socket != null && socket.isConnected()) { size = in.read(w); if (size <= 0) { continue; } str = new String(w, 0, size, "UTF-8"); addText(str); } } catch (Exception e) { addText("通信に失敗しました。"); } } private void disconnect() { try { socket.close(); socket = null; } catch (Exception e) { } } @Override public void onClick(View v) { Thread thread = new Thread(new Runnable() { @Override
  • 7. public void run() { error = false; try { if (socket != null && socket.isConnected()) { byte[] w = editText.getText().toString().getBytes("UTF8"); out.write(w); out.flush(); } } catch (Exception e) { error = true; } handler.post(new Runnable() { public void run() { if (error) { addText(" 通 信 に 失 敗 し ま した"); } else { editText.setText("", TextView.BufferType.NORMAL); } } }); } }); thread.start(); } } ソースコード(サーバ側) Eclipse で新規 Java プロジェクト『chatserver』を作成します。作成したら、src フォルダ の直下に、 『ChatServer.java』 『CharServerThread.java』2 つの java ファイルを作成しま す。ソースコードはそれぞれ以下のように記述します。 ○ChatServer.java
  • 8. package com.example; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /** * * This class launches the web application in an embedded Jetty container. * This is the entry point to your application. The Java command that is used for * launching should fire this main method. * */ public class ChatServer { public void start(int port) { ServerSocket server; Socket socket; ChatServerThread thread; try { server = new ServerSocket(port); System.err.println("ChatServer start" + "¥nIP Address:" InetAddress.getLocalHost().getHostAddress() + "¥nPort:" + port); while (true) { try { socket = server.accept(); thread = new ChatServerThread(socket); thread.start(); } catch (IOException e) { System.out.println(e); } +
  • 9. } } catch (IOException e) { System.err.println(e); } } public static void main(String[] args) throws Exception{ ChatServer server = new ChatServer(); server.start(8080); } } ○ChatServerThread.java package com.example; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class ChatServerThread extends Thread { private static List<ChatServerThread> ArrayList<ChatServerThread>(); private Socket socket; public ChatServerThread(Socket socket) { super(); this.socket = socket; threads.add(this); } threads = new
  • 10. public void run() { InputStream in = null; String message; int size; byte[] w = new byte[10240]; try { System.err.println("ChatServerThread start"); in = socket.getInputStream(); while(true) { try { size = in.read(w); if (size <= 0) { throw new IOException(); } message = new String(w, 0, size, "UTF8"); System.out.println(message); sendMessageAll(message); } catch(IOException e) { System.out.println("ChatServerThread stop"); socket.close(); threads.remove(this); return; } } } catch (IOException e) { System.err.println(e); } } public void sendMessageAll(String message) { for (ChatServerThread thread : threads) {
  • 11. if (thread.isAlive()) { thread.sendMessage(this, message); } } System.out.println(message); } public void sendMessage(ChatServerThread talker, String message) { try { OutputStream out = socket.getOutputStream(); byte[] w = message.getBytes("UTF8"); out.write(w); out.flush(); } catch (IOException e) { } } } ソースを記述したら、Java アプリケーションとして実行してください。 その後、Android アプリを起動します。 2. HTTP 通信を行う Android アプリ HTTP 通信の GET/POST メソッドを行ってネット上の情報を表示するアプリを作成します。 ソースコード Eclipse を開いて、パッケージエクスプローラーで右クリックし、[新規]->[Android プロジ ェクト]を選択します。 プロジェクト名は 「HttpEx」 としてください。 Target SDK と Compile With は Android4.0(IceCreamSandwich)を選びます。ActivityName は「HttpEx」としま しょう。 プロジェクトが作成出来たら、src.com.example.httpex フォルダの HttpEx.java ファイル を以下のように編集してください。 また、AndroidManifest.xml を開き、 『Permission』タブの中の Add ボタンをクリックし て、 『User Permission』を選択します。Name は『android.permission.INTERNET』を選 択してください。 package com.example.httpex;
  • 12. import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class HttpEx extends Activity implements View.OnClickListener{ private static final int WC = LinearLayout.LayoutParams.WRAP_CONTENT; private static final int MP = LinearLayout.LayoutParams.MATCH_PARENT; private EditText editText; // リクエスト先の URL private static final String URL = "http://httpserverex.herokuapp.com/hello"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); // レイアウトの生成 LinearLayout layout = new LinearLayout(this); layout.setBackgroundColor(Color.rgb(255, 255, 255));
  • 13. layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); // エディットテキストの生成 editText = new EditText(this); editText.setText("", EditText.BufferType.NORMAL); editText.setLayoutParams(new LinearLayout.LayoutParams(MP, WC)); layout.addView(editText); layout.addView(makeButton("HTTP 通信", "read")); } /** * ボタンの生成 * @param text * @param tag * @return */ private Button makeButton(String text, String tag) { Button button = new Button(this); button.setText(text); button.setTag(tag); button.setOnClickListener(this); button.setLayoutParams(new LinearLayout.LayoutParams(WC, WC)); return button; } @Override public void onClick(View arg0) { String tag = (String) arg0.getTag(); if (tag.equals("read")) { Thread thread = new Thread(new Runnable() { String text = null;
  • 14. @Override public void run() { // HTTP 通信 try { text = String(httpToData(URL)); } catch (Exception e) { text = null; } Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { if (text != null) { editText.setText(text, TextView.BufferType.EDITABLE); } else { HttpEx.showDialog(HttpEx.this, "エラー", "読み込みに失敗しました"); } } }); } }); thread.start(); } } public static byte[] httpToData(String path) throws Exception { byte[] write = new byte[1024]; HttpURLConnection connection = null; InputStream in = null; ByteArrayOutputStream out = null; try { // HTTP 接続のオープン new
  • 15. URL url = new URL(path); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); in = connection.getInputStream(); out = new ByteArrayOutputStream(); int size; while ((size = in.read(write)) > 0) { out.write(write, 0, size); } out.close(); in.close(); connection.disconnect(); return out.toByteArray(); } catch (Exception e) { try { if (connection != null) { connection.disconnect(); } if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e2) { } throw e; } } private static void showDialog(Context context, String title, String text) { AlertDialog.Builder ad = new AlertDialog.Builder(context); ad.setTitle(title);
  • 16. ad.setMessage(text); ad.setPositiveButton("OK", null); ad.show(); } } ソースが記述出来たら、Android Application として実行してください。 <演習> GET リクエストで上記の URL にアクセスしていますが、POST 用のボタンを追加し、そ のボタンをクリックされた場合は、POST リクエストを行うように修正しなさい。 また、リクエストクエリも追加で送信出来るように修正しなさい。