クライアントサーバー実装T_Client
にこのクライアントクラス「T_Client」があります。
public class T_Client{
private static final String TAG = "T_Client";
private static String serverIP = "192.168.2.5";
private static int port = 4444;
private InetAddress serverAddr = null;
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
Object objIn;
public void send(MessageCustom _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
// out.close();
Log.i("Send Method", "Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e("Send Method", ex.toString());
}
}
}
public void stopClient() {
running = false;
}
public void run() {
running = true;
try {
// here you must put your computer's IP address.
serverAddr = InetAddress.getByName(serverIP);
Log.i("TCP Client", "C: Connecting...");
// create a socket to make the connection with the server
sock = new Socket(serverAddr, port);
try {
// send the message to the server
out = new ObjectOutputStream(sock.getOutputStream());
// receive the message which the server sends back
in = new ObjectInputStream(sock.getInputStream());
Log.i("TCP Client", "C: Connected.");
// in this while the client listens for the messages sent by the
// server
while (running) {
objIn = in.readObject();
Log.i("Object Read", objIn.toString());
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn
+ "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
// the socket must be closed. It is not possible to reconnect to
// this socket
// after it is closed, which means a new socket instance has to
// be created.
out.close();
in.close();
sock.close();
Log.i(TAG, "Closing socket: " + sock);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}
そして、サーバー (objIn) からオブジェクトを取得し、それを UI スレッドに渡して、そこでいくつかの UI 更新を実行できるようにしたいと考えています。少し調べてみると、ハンドラーを使用する必要があると思いますが、実装について頭を悩ませることはできません。
私の場合にハンドラーを実装し、メインアクティビティで呼び出しを行う方法の簡単な例を誰かに教えてもらえますか? または、簡単なチュートリアルを教えてください。Android Developers サイトのチュートリアルに従ってみましたが、複雑すぎます。