336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
안드로이드 상에서 소캣통신 테스트를 위해 간단이 짜깁기해 만들어본 App.

호기심에 안드로이드로 서버를 구성해봤는데 뭐 당연한 결과겠지만 문제없이 잘 돌아감

좀더 이것저것 손볼까하다 귀차니즘에 결국은 컴팩트한 echo chat app.

Server
src

package test.server.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class main extends Activity {
    /** Called when the activity is first created. */
 
 private ServerSocket socket;
 private int port = 9999;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        try {
   socket = new ServerSocket(port);
  }catch (IOException e) {
   Log.d("DMSG", "Error : " + e);
   //e.printStackTrace();
  }
  
  while(true) {
   try {
    Socket sock = socket.accept();
    Thread checkUpdate = new echoThread(sock);
    checkUpdate.start();
   }
   catch(IOException ex) {
   }
  }
    }
   
    class echoThread extends Thread {
     
    private Socket sock;

    public echoThread(Socket sock)
    {
       this.sock = sock;
    }
   
    public void run() {
     try {
          InetAddress addr = sock.getInetAddress();
          System.out.println(addr.getHostAddress() + "Connected..");

          BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));

          String msg = null;
         
          while((msg = br.readLine()) != null)
          {
             Log.d("DMSG", "From " + addr.getHostAddress() + "'s Message: " + msg);
             pw.println(msg + " ..(from server)");
             pw.flush();

             if(msg.equals("exit")){
                break;
             }
          }

          pw.close();
          br.close();
          sock.close();
       }
       catch(Exception e)
       {
          Log.d("DMSG", "Error : " + e);
       }
    }
  
 };
}


Client
src

package test.client.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import test.client.tcp.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

 

/* Called when the activity is first created. */
public class main extends Activity {

 private String strMsg = "";
 private String read = "";
 private String html = "";
 private Handler mHandler;
 private Socket socket;
 private BufferedReader networkReader;
 private BufferedWriter networkWriter;
 private String ip ="127.0.0.1";
 private int port = 9999;
 private PrintWriter out;
 
 private ListView mConversationView;
 
 private ArrayAdapter<String> mConversationArrayAdapter;
 
 @Override
 protected void onStop() {
  //TODO Auto-generated method stub
  super.onStop();
  try {
   Log.d("DMSG", "Socket close...ok");
   socket.close();
  }catch (IOException e) {
   Log.d("DMSG", "Socket close fail!");
   //TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  mHandler = new Handler();
  
  try {
   setSocket(ip,port);
   Log.d("DMSG", "OK");
  }catch (IOException e1) {
   //TODO Auto-generated catch block
   e1.printStackTrace();
   Log.d("DMSG", "Error : " + e1);
  }
  
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
       
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);
       
        mConversationView.setTextFilterEnabled(true);        
  
  Button btn = (Button) findViewById(R.id.Button01);
  
  btn.setOnClickListener(new OnClickListener() {
   EditText et = (EditText) findViewById(R.id.EditText01);
   public void onClick(View v) {
    if (et.getText().toString() != null || !et.getText().toString().equals("")) {
     /*PrintWriter*/ out = new PrintWriter(networkWriter,true);
     String return_msg = et.getText().toString();
     out.println(return_msg);
     out.flush();
     strMsg = "Send Message : " + return_msg;
     mConversationArrayAdapter.add(strMsg);
     Log.d("DMSG", "Msg = " + return_msg);
     
     et.setText("");
    } 
   }
  });
  
  try {
   Thread checkUpdate = new echoThread(mConversationArrayAdapter, out);
   checkUpdate.start();
  }
  catch(Exception ex) {
   Log.d ("DMSG", "Error : " + ex);
  }
 }

 class echoThread extends Thread {
  
  ArrayAdapter<String> conversationArrayAdapter;
  PrintWriter pw;
  String tmp;
  
  public echoThread(ArrayAdapter<String> mConversationArrayAdapter, PrintWriter out)
  {
   this.conversationArrayAdapter = mConversationArrayAdapter;
   this.pw = out;
   Log.d("DMSG", "Thread init.");
  }
  
  public void run() {
   try {
    while (true) {
     Log.w("DMSG","chatting is running");
     
     try {
      Thread.sleep(100);
     } catch (Exception e) {
      Log.d("DMSG", "Error : " + e);
     }
     
     read = null;
     while((read = networkReader.readLine()) != null)
     {
               Log.d("DMSG", "receive msg");
               mHandler.post(showUpdate);
     }

    }
   }catch (Exception e) {
    Log.d("DMSG", "Client Thread Error!" + e);
   }
  }
 };
 
 private Runnable showUpdate = new Runnable() {
  public void run() {
   Toast.makeText(main.this,"Coming word: " + html, Toast.LENGTH_SHORT).show();
   mConversationArrayAdapter.add("Receive Message : " + read);
  }
 };
 
 public void setSocket(String ip,int port)throws IOException { 
  try {
   socket =new Socket(ip, port);
   networkWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
   networkReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   Log.d("DMSG", "Client Socket Init...");
  }catch (IOException e) {
   System.out.println(e);
   e.printStackTrace();
   Log.d("DMSG", "Client Socket Init fail!");
  }
 }
}


xml

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <ListView android:id="@+id/in"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stackFromBottom="true"
        android:transcriptMode="alwaysScroll"
        android:layout_weight="1"/>
   <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <EditText android:id="@+id/EditText01"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     android:layout_weight="1"/>
 
    <Button android:id="@+id/Button01"
     android:layout_width="80dip"
     android:layout_height="wrap_content"
     android:text="Send"/>
   </LinearLayout>
</LinearLayout>


xml(message.xml)
 <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="18sp"
    android:padding="5dp"/>

참고로 위의 App를 실행하기 위해선 AndroidManifest.xml에 아래와 같이 INTERNET permission을 추가해 주어야함

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

실행화면(client)

참고로 실행 장비가 Odroid-T라서 해상도및 비율이 일판 스마트폰들과는 조금 다르게 보임

'Programming > android' 카테고리의 다른 글

android에서 external command 사용하는 방법  (0) 2010.09.03
Supporting Multiple Screens  (0) 2010.05.20
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

지금은 인내의 시간!

매처럼 날려면 닭과 다투지 마라!

'끄적임' 카테고리의 다른 글

garmin connect IQ SDK  (0) 2016.05.09
내맘대로 계란말이  (0) 2010.09.17
결혼 뭐 하러 하노?  (0) 2010.09.07
계란 볶음밥  (0) 2010.09.06
2011 Mini Countryman!!  (0) 2010.09.03

+ Recent posts