** 안드로이드 공부하면서 수집한 정보를 토대로 
 최대한 이해하기 쉽게 소스를 정리해 보았습니다.
 안드로이드 클라이언트는 소스를 최소화 하기 위해 서버 접속과 메시지 수신부만 구현하였습니다.
 송신부는 PrintWriter를 사용하여 직접한 번 구현해 보시기 바랍니다. ^^

 

1.구성

  • 자바 채팅서버
  • 자바 채팅클라이언트
  • 안드로이드 채팅클라이언트

2.목적

자바 채팅클라이언트와 안드로이드 채팅클라이언트 간의 메시지 송수신 확인

3.실행방법

3-1.서버구동




3-2.자바클라이언트 구동







3-3.테스트 방법



4.소스


4-1. 자바 서버 소스

package chap8;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

public class ChatServer {
 private final static int SERVER_PORT = 10001;
 public static void main(String[] args) {
  try{
   ServerSocket server = new ServerSocket(SERVER_PORT);
   HashMap hm = new HashMap();
   System.out.println("waiting connection..");
   while(true){
    Socket sock = server.accept();
    ChatThread chatthread = new ChatThread(sock, hm);
    chatthread.start();
   }
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}

class ChatThread extends Thread{
 private final Socket sock ; 
 private final HashMap hm ; 
 private String id;   

 private BufferedReader br;
 private boolean initFlag = false;
 public ChatThread(Socket sock, HashMap hm){
  this.sock = sock;
  this.hm = hm;
  
  try{
   PrintWriter pw = new PrintWriter( new OutputStreamWriter(sock.getOutputStream()) );
   br = new BufferedReader( new InputStreamReader(sock.getInputStream()) );
   id = br.readLine();
   broadcast(id + " is connected");
   System.out.println("connected user id is "+id);
   synchronized(hm){
    hm.put(this.id, pw);
   }
   initFlag = true;
   
  }
  catch(Exception ex){ System.out.println(ex); }
 }
 public void run(){
  try{
   String line = null;
   while( (line=br.readLine() )!= null ) {
    if(line.equals("/quit"))break;
    
    if(line.indexOf("/to")==0)sendmsg(line);
    else broadcast(id+":"+line);
   }
  }
  catch(Exception ex){}
  finally{
   synchronized(hm){
    hm.remove(id);
   }
   broadcast(id+" is terminated");
   try { if(sock != null)sock.close();}
   catch(Exception ex){}
  }
 }
 public void sendmsg(String msg){
  int start = msg.indexOf(" ")+1;
  int end = msg.indexOf(" ",start);
  
  if(end != -1){
   String to = msg.substring(start,end);
   String msg2 = msg.substring(end+1);
   Object obj = hm.get(to);
   if(obj != null){
    PrintWriter pw = (PrintWriter)obj;
    pw.println(id+" tells : " + msg2);
    pw.flush();
   }
  }
 }
 public void broadcast(String msg){
  synchronized(hm){
   Collection collection = hm.values();
   Iterator iter = collection.iterator();
   while(iter.hasNext()){
    PrintWriter pw = (PrintWriter)iter.next();
    pw.println(msg);
    pw.flush();
   }
  }
 }
}


4-2. 자바 클라이언트 소스

package chap8;

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

public class ChatClient {

 public static void main(String[] args) {
  if(args.length != 2){
   System.out.println("Usage : java ChatClient {Your Id} {Server IP}");
   System.exit(1);
  }
  
  Socket sock = null;
  BufferedReader br = null;
  PrintWriter pw = null;
  boolean endflag = false;
  try{
   sock = new Socket(args[1],10001);
   pw = new PrintWriter( new OutputStreamWriter( sock.getOutputStream() ) );
   br = new BufferedReader( new InputStreamReader( sock.getInputStream() ) );
   BufferedReader keyboard = new BufferedReader( new InputStreamReader(System.in) );
   
   pw.println(args[0]) ;
   pw.flush();
   
   InputThread it = new InputThread(sock, br);
   it.start();

   String line = null;
   while( (line = keyboard.readLine()) != null){
    pw.println(line);
    pw.flush();
    if(line.equals("/quit")){
     endflag = true;
     break;
    }
   }
   System.out.println("Terminating.");
  }
  catch(Exception ex){
   if(!endflag)System.out.println(ex);
  }
  finally {
   try{
    if(pw != null)pw.close();
   }
   catch(Exception ex){}
   try {
    if(br != null)br.close();
   }
   catch(Exception ex){}
   try {
    if(sock != null)sock.close();
   }
   catch(Exception ex){}   
  }
 }
}

class InputThread extends Thread {
 private Socket sock = null;
 private BufferedReader br = null;
 public InputThread(Socket sock, BufferedReader br){
  this.sock = sock;
  this.br = br;
 }
 
 public void run(){
  try{
   String line = null;
   while( (line=br.readLine()) != null){
    System.out.println(line);
   }
  }
  catch(Exception ex){}
  finally {
   try {
    if(br != null)br.close();
   }catch(Exception ex){}
   try{
    if(sock != null)sock.close();
   }catch(Exception ex){}
  }
 }
}


4-3. 안드로이드 클라이언트 소스

package Soket.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SoketChat extends Activity {
 private final static String IP = "10.0.2.2";
 private final static int PORT = 10001;
 private final static String LOGIN_ID="AndroidClient";
 
 private TextView lblReceive;
 private String txtReceive;
 private Socket socket;
 private InputStream in;
 private OutputStream out;
 private final Handler handler = new Handler();
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
       
        RelativeLayout layout = new RelativeLayout(this);
        layout.setBackgroundColor(Color.rgb(255, 255, 255));
        setContentView(layout);

        // -- label for messages
        lblReceive = new TextView(this);
        lblReceive.setId(1);
        lblReceive.setText("");
        lblReceive.setTextSize(16.0f);
        lblReceive.setTextColor(Color.rgb(0,0,0));
        RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(320,400);
        lblReceive.setLayoutParams(param1);
        layout.addView(lblReceive);

        // -- Thread for Connection
        Thread cThread = new Thread(){public void run(){
         try{
          connect(IP,PORT);
         } catch(Exception e){} }
        };
        cThread.start();
    }
    private void connect(String ip, int port){
     int size;
     byte[] w = new byte[10240];
     txtReceive="";
     try{
      socket = new Socket(ip,port);
      if(socket != null) {
       in = socket.getInputStream();
       out = socket.getOutputStream();

       PrintWriter pw = new PrintWriter( new OutputStreamWriter( out ) );
       pw.println(LOGIN_ID);
       pw.flush() ;
       
       while(socket != null && socket.isConnected()){
        size = in.read(w);
        if(size<=0)continue;
        txtReceive = new String(w,0,size,"UTF-8");
        handler.post(new Runnable(){
         public void run() {
          lblReceive.setText( lblReceive.getText()+txtReceive );
         }
        });
       }
      }
     } catch (Exception ex) {Log.e("socket",ex.toString());}
    }
}