반응형












  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:layout_width="match_parent"  
  4. android:layout_height="match_parent"  
  5. android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="100dp"  
  10.         android:text=""  
  11.         android:id="@+id/textView"  
  12.         android:layout_alignParentLeft="true"  
  13.         android:layout_marginLeft="0dp"  
  14.   
  15.         android:layout_above="@+id/linearLayout"  
  16.         android:layout_alignParentTop="true" />  
  17.   
  18.     <LinearLayout  
  19.         android:orientation="horizontal"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="46dp"  
  22.         android:layout_alignParentBottom="true"  
  23.         android:layout_alignParentLeft="true"  
  24.         android:layout_alignParentStart="true"  
  25.         android:id="@+id/linearLayout"  
  26.         android:weightSum="1">  
  27.   
  28.         <EditText  
  29.             android:layout_width="wrap_content"  
  30.             android:layout_height="wrap_content"  
  31.             android:id="@+id/editText"  
  32.             android:layout_alignParentLeft="true"  
  33.             android:layout_alignParentTop="true"  
  34.             android:layout_weight="1.00" />  
  35.   
  36.         <Button  
  37.             android:layout_width="wrap_content"  
  38.             android:layout_height="wrap_content"  
  39.             android:text="전송"  
  40.             android:id="@+id/button"  
  41.             android:layout_alignParentLeft="true"  
  42.             android:layout_alignParentTop="true" />  
  43.     </LinearLayout>  
  44.   
  45. </RelativeLayout>  




  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.webnautes.client" >  
  4.   
  5.     <uses-permission android:name="android.permission.INTERNET"/>  
  6.   
  7.     <application  
  8.         android:allowBackup="true"  
  9.         android:icon="@mipmap/ic_launcher"  
  10.         android:label="@string/app_name"  
  11.         android:supportsRtl="true"  
  12.         android:theme="@style/AppTheme" >  
  13.         <activity android:name=".MainActivity" >  
  14.             <intent-filter>  
  15.                 <action android:name="android.intent.action.MAIN" />  
  16.   
  17.                 <category android:name="android.intent.category.LAUNCHER" />  
  18.             </intent-filter>  
  19.         </activity>  
  20.     </application>  
  21.   
  22. </manifest>  





package com.example.webnautes.client;


import android.app.Activity;

import android.os.AsyncTask;

import android.os.Build;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

import java.net.UnknownHostException;




public class MainActivity extends Activity {


    private EditText textField;

    private Button button;

    private TextView textView;

    private Socket client;

    private PrintWriter printwriter;

    private BufferedReader bufferedReader;


    //Genymotion에서 가상머신의 IP대역이 192.168.56.X이고

    //PC의 vboxnet0 인터페이스 아이피가 192.168.56.1임...

    private String SERVER_IP = "192.168.56.1";



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        textField = (EditText) findViewById(R.id.editText);

        button = (Button) findViewById(R.id.button);

        textView = (TextView) findViewById(R.id.textView);



        ChatOperator chatOperator = new ChatOperator();

        chatOperator.execute();

    }



    private class ChatOperator extends AsyncTask<Void, Void, Void> {


        @Override

        protected Void doInBackground(Void... arg0) {

            try {

                client = new Socket(SERVER_IP, 9999); // Creating the server socket.


                if (client != null) {

                    //자동 flushing 기능이 있는 PrintWriter 객체를 생성한다.

                    //client.getOutputStream() 서버에 출력하기 위한 스트림을 얻는다.

                    printwriter = new PrintWriter(client.getOutputStream(), true);

                    InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());


                    //입력 스트림 inputStreamReader에 대해 기본 크기의 버퍼를 갖는 객체를 생성한다.

                    bufferedReader = new BufferedReader(inputStreamReader);

                } else {

                    System.out.println("Server has not bean started on port 9999.");

                }

            } catch (UnknownHostException e) {

                System.out.println("Faild to connect server " + SERVER_IP);

                e.printStackTrace();

            } catch (IOException e) {

                System.out.println("Faild to connect server " + SERVER_IP);

                e.printStackTrace();

            }

            return null;

        }


        /**

         * Following method is executed at the end of doInBackground method.

         */

        @Override

        protected void onPostExecute(Void result) {

            button.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {


                    String text = textField.getText().toString();


                    final Sender messageSender = new Sender(); // Initialize chat sender AsyncTask.

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                        messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, text);

                    } else {

                        messageSender.execute(text);

                    }

                }

            });


            if ( client != null) {

                Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.

                receiver.execute();

            }


        }


    }


    /**

     * This AsyncTask continuously reads the input buffer and show the chat

     * message if a message is availble.

     */

    private class Receiver extends AsyncTask<Void, Void, Void> {


        private String message;


        @Override

        protected Void doInBackground(Void... params) {

            while (true) {

                try {

                    //스트림으로부터 읽어올수 있으면 true를 반환한다.

                    if (bufferedReader.ready()) {

                        //'\n', '\r'을 만날 때까지 읽어온다.(한줄을 읽어온다.)

                        message = bufferedReader.readLine();

                        publishProgress(null);

                    }

                } catch (UnknownHostException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                }


                try {

                    Thread.sleep(500);

                } catch (InterruptedException ie) {

                }

            }

        }


        //publishProgress(null)에 의해서 호출된다. '

        //서버에서 전달받은 문자열을 읽어서 화면에 출력해준다.

        @Override

        protected void onProgressUpdate(Void... values) {

            textView.append("Server: " + message + "\n");

        }


    }


    /**

     * This AsyncTask sends the chat message through the output stream.

     */

    private class Sender extends AsyncTask<String, String, Void> {


        private String message;


        @Override

        protected Void doInBackground(String... params) {

            message = params[0];


            //문자열을 스트림에 기록한다.

            printwriter.write(message + "\n");


            //스트림을 플러쉬한다.

            printwriter.flush();


            return null;

        }


        //클라이언트에서 입력한 문자열을 화면에 출력한다.

        @Override

        protected void onPostExecute(Void result) {

            textField.setText(""); // Clear the chat box

            textView.append("Client: " + message + "\n");

        }

    }

}







문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts