달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
반응형
2013. 3. 28. 11:43

안드로이드 - 소켓통신 안드로이드 이야기2013. 3. 28. 11:43

728x90
반응형

안드로이드 - 소켓통신

출처: http://webprogrammer.tistory.com/1815

출처는 명확하지 않음-_-;; 원작성자 분에게는 죄송합니다;
앞의 2009/03/10 - [Computer Science/Android] - [펌]Android에서의 TCP/IP 통신 글의 코드와 매우 유사하긴 하지만.. 뭔가 더 간단하고 예제는 많을 수록 좋으므로;(-_-)

SocketTest.java 

Java:

public class SocketTest extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle icicle) { 
        super.onCreate(icicle); 
        setContentView(R.layout.main); 
        
        Thread sThread = new Thread(new TCPServer()); 
        Thread cThread = new Thread(new TCPClient()); 
        
        sThread.start(); 
        try { 
               Thread.sleep(1000); 
          } catch (InterruptedException e) { } 
        
          cThread.start(); 
    } 
} 


TCPServer.java 

Java:

public class TCPServer implements Runnable{ 
      
    public static final String SERVERIP = "127.0.0.1"; 
    public static final int SERVERPORT = 4444; 
          
    public void run() { 
         try { 
              Log.d("TCP", "S: Connecting..."); 
              
              ServerSocket serverSocket = new ServerSocket(SERVERPORT); 
              while (true) { 
                 Socket client = serverSocket.accept(); 
                 Log.d("TCP", "S: Receiving..."); 
                 try { 
                      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
                      String str = in.readLine(); 
                      Log.d("TCP", "S: Received: '" + str + "'"); 
                    } catch(Exception e) { 
                        Log.e("TCP", "S: Error", e); 
                    } finally { 
                         client.close(); 
                         Log.d("TCP", "S: Done."); 
                    } 

              } 
              
         } catch (Exception e) { 
           Log.e("TCP", "S: Error", e); 
         } 
    } 
} 


TCPClient.java 

Java:

public class TCPClient implements Runnable { 

      
    public void run() { 
         try { 
            
           InetAddress serverAddr = InetAddress.getByName(UDPServer.SERVERIP); 
            
           Log.d("TCP", "C: Connecting..."); 
           Socket socket = new Socket(serverAddr, TCPServer.SERVERPORT); 
           String message = "Hello from Client"; 
               try { 
                Log.d("TCP", "C: Sending: '" + message + "'"); 
                PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
                
                out.println(message); 
                Log.d("TCP", "C: Sent."); 
                  Log.d("TCP", "C: Done."); 
                
             } catch(Exception e) { 
                 Log.e("TCP", "S: Error", e); 
                } finally { 
                  socket.close(); 
                } 
         } catch (Exception e) { 
              Log.e("TCP", "C: Error", e); 
         } 
    } 
} 




AndroidManifest.xml 

XML:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.e2esp.socket.test">
 
    <application android:icon="@drawable/icon"> 
        <activity class=".SocketTest" android:label="@string/app_name"> 
            <intent-filter> 
                <action android:value="android.intent.action.MAIN" /> 
                <category android:value="android.intent.category.LAUNCHER" /> 
            </intent-filter> 
        </activity> 
    </application> 
</manifest> 



출처 : http://plucky.tistory.com/13

728x90
반응형
:
Posted by mapagilove
728x90
반응형

 

안드로이드 - DB file을 assets디렉토리에서 폰으로 복사 이동하는 예제

원본출처: http://blog.daum.net/dayhyub/53

 

 안드로이드 개발시 종목기본정보를

DB에 저장하다보니

애뮬레이터에서는 잘 돌던 프로그램이

폰으로 옮겼을 때 DB가 없어서

에러가 났다.

그래서 이를 해결하는 방법을 찾다보니

안드로이드에선 주로 assets디렉토리에 파일을 두고

프로그램 실행시 DB로 카피하는 식의 방식을 쓰고 있어

인터넷에서 예제를 구해 나름

작업해보았다.

 

 [함수예제]
  private void copyDB() {
  // TODO Auto-generated method stub
  String dir="/data/data/com.example.neojprice/databases/";
  String fname = "JMaster.db";
  File folder =new File(dir);
  if(folder.exists()){
   
  }else{
   folder.mkdirs();
   System.out.println("폴더 생성!!!!");
  }
  AssetManager aman = getResources().getAssets();
  File ofile = new File(dir+fname);
  ofile.delete(); 
  InputStream in = null;
  FileOutputStream out = null;
  long filesize=0;
  
  try{
   in = aman.open(fname,AssetManager.ACCESS_BUFFER);
   filesize = in.available();
   
   if(ofile.length() <=0){
    byte[] tmpbyte = new byte[(int)filesize];
    in.read(tmpbyte);
    in.close();
    ofile.createNewFile();
    out = new FileOutputStream(ofile);
    out.write(tmpbyte);
    out.close();
   }else{
    
    System.out.println("DB있음!!!");
   }
  }catch(IOException e){
   System.out.println("DB생성 오류 ["+e+"]");
  }
  
 }

728x90
반응형
:
Posted by mapagilove
728x90
반응형

안드로이드 - 소켓 프로그래밍 (TCP/IP) Server&Client 예제 (쓰레드 활용)

원본출처: http://warmz.tistory.com/597


TcpIpServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class TcpIpServer implements Runnable {
    ServerSocket serverSocket;
    Thread[] threadArr;
 
    public static void main(String[] args) {
        // 5개의 쓰레드를 생성하는 서버를 생성한다.
        TcpIpServer server = new TcpIpServer(5);
        server.start();
    }
 
    public TcpIpServer(int num) {
        try {
            // 서버 소켓을 생성하여 7777번 포트와 바인딩.
            serverSocket = new ServerSocket(7777);
            System.out.println(getTime() + " 서버가 준비되었습니다.");
 
            threadArr = new Thread[num];
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public void start() {
        for (int i = 0; i < threadArr.length; i++) {
            threadArr[i] = new Thread(this);
            threadArr[i].start();
        }
    }
 
    @Override
    public void run() {
        while (true) {
            try {
                System.out.println(getTime() + " 가 연결 요청을 기다립니다.");
 
                Socket socket = serverSocket.accept();
                System.out.println(getTime() + " " + socket.getInetAddress()
                        + "로부터 연결요청이 들어왔습니다.");
 
                OutputStream out = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(out);
 
                dos.writeUTF("[Notice] Test Message1 from Server");
                System.out.println(getTime() + " 데이터를 전송하였습니다.");
 
                dos.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    static String getTime() {
        String name = Thread.currentThread().getName();
        SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]");
        return f.format(new Date()) + name;
    }
}

 
TcpIpClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;
 
 
public class TcpIpClient {
    public static void main(String[] args) {
        try{
            String serverIp = "127.0.0.1";
 
            // 소켓을 생성하여 연결을 요청한다.
            System.out.println("서버에 연결중입니다. 서버IP : " + serverIp);
            Socket socket = new Socket(serverIp, 7777);
             
            // 소켓의 입력스트림을 얻는다.
            InputStream in = socket.getInputStream();
            DataInputStream dis = new DataInputStream(in);
             
            // 소켓으로부터 받은 데이터를 출력한다.
            System.out.println("서버로부터 받은 메세지 : " + dis.readUTF());
            System.out.println("연결을 종료합니다.");
             
            dis.close();
            socket.close();
            System.out.println("연결이 종료되었습니다.");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 
결과) 서버

[08:22:23]main 서버가 준비되었습니다.

[08:22:23]Thread-0 가 연결 요청을 기다립니다.

[08:22:23]Thread-1 가 연결 요청을 기다립니다.

[08:22:23]Thread-2 가 연결 요청을 기다립니다.

[08:22:23]Thread-3 가 연결 요청을 기다립니다.

[08:22:23]Thread-4 가 연결 요청을 기다립니다.

[08:22:27]Thread-0 /127.0.0.1로부터 연결요청이 들어왔습니다.

[08:22:27]Thread-0 데이터를 전송하였습니다.

[08:22:27]Thread-0 가 연결 요청을 기다립니다.


결과) 클라이언트

서버에 연결중입니다. 서버IP : 127.0.0.1

서버로부터 받은 메세지 : [Notice] Test Message1 from Server

연결을 종료합니다.

연결이 종료되었습니다.

728x90
반응형
:
Posted by mapagilove
728x90
반응형

안드로이드 - 전화번호부 관리 프로그램

원본 출처: http://warmz.tistory.com/497

* 친구 부탁으로 간단하게 만든 전화번호부 관리 프로그램.


PDApplication.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package PD;
 
import java.io.IOException;
 
/**
 * represents the application itself. */
 
public class PDApplication {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // 실행시 전화번호부 파일 이름을 쓰지 않으면 에러 메세지 출력
        /*
        if (args.length == 0) {
            System.err.println("You must provide the name of the file"
                    + " that contains the phone directory.");
            System.exit(1);
        }
        */
        PhoneDirectory phoneDirectory = new PhoneDirectory();
        // 전화번호부 기능을 수행할 클래스 생성.
         
        try {
            phoneDirectory.loadData("pd.txt"); 
            // 파일로부터 저장된 연락처들을 읽어들인다.
        } catch (IOException e) {
            e.printStackTrace();
        }
         
        PDGUI phoneDirectoryInterface = new PDGUI();    // GUI 생성
        phoneDirectoryInterface.processCommands(phoneDirectory);
        // 전화번호부 기능을 활성화
    }
}


DirectoryEntry.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package PD;
 
/**
 * represent a pair of name and number.
 * 쌍으로 이루어진 이름과 전화번호를 나타내는 클래스. */
 
public class DirectoryEntry {
    private String name;
    private String number;
 
    /** 연락처를 추가하는 함수 */
    public DirectoryEntry(String name, String number) {
        this.name = name;
        this.number = number;
    }
 
    /** 이름을 반환하는 함수 */
    public String getName() {
        return name;
    }
 
    /** 전화번호를 반환하는 함수  */
    public String getNumber() {
        return number;
    }
 
    /** 전화번호를 수정하는 함수  */
    public void setNumber(String number) {
        this.number = number;
    }
}

 
PhoneDirectory.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package PD;
 
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
 
/**
 * represents the phone directory, i.e. collection of entries.
 * provides lookup, add, and remove operations
 * 전화번호부 기능을 수행하는 클래스.
 * 보기, 추가 , 삭제, 저장기능을 수행한다. */
 
public class PhoneDirectory {
    private static final int INITIAL_CAPACITY = 100;    // 최대 저장 갯수
    private int capacity = INITIAL_CAPACITY;            // 최대 저장 갯수 설정
    private int size = 0;                               // 현재 저장 갯수
    private DirectoryEntry[] theDirectory =
        new DirectoryEntry[capacity];               // 전화번호부를 생성
    private String sourceName = null;               // 전화번호부 파일
    private boolean modified = false;               // 전화번호부 수정 여부
 
    /** 파일에 기록된 전화번호부를 읽어오는 함수 */
    public void loadData(String sourceName) throws IOException {
        this.sourceName = sourceName;
        try {
            BufferedReader in =
                new BufferedReader(new FileReader(sourceName));
            // 'sourceName' 파일로부터 데이터를 읽어 버퍼(in)에 저장한다.
             
            String name, number;
            while ((name = in.readLine()) != null) {    // 끝까지 읽는다.
                if ((number = in.readLine()) == null) { // 전화번호 값이 null이면
                    break;                              // 중지
                }
                add(name, number);      // 연락처를 추가한다.
            }
            in.close();
        } catch (FileNotFoundException ex) {
            return;
        }
    }
 
    /** 연락처를 추가하거나 수정하는 함수 */
    public String addOrChangeEntry(String name, String number) {
        String oldNumber = null;
        int index = find(name);     // 이름으로 저장된 연락처를 찾는다.
         
        if (index > -1) {            // 해당 이름을 찾았으면
            oldNumber = theDirectory[index].getNumber();    // 기존 전화번호를 임시 변수에 저장하고
            theDirectory[index].setNumber(number);          // 새로운 전화번호를 저장한다.
        } else {                    // 해당 이름을 못 찾았으면
            add(name, number);      // 새로 추가한다.
        }
        modified = true;            // 수정여부를 true로 고침.
         
        return oldNumber;           // 기존 전화번호를 반환한다.
    }
 
    /** 저장된 전화번호를 보여주는 함수 */
    public String lookupEntry(String name) {
        int index = find(name);     // 'name'으로 검색한다.
        if (index > -1) {            // 찾았으면
            return theDirectory[index].getNumber(); // 전화번호를 반환한다.
        } else {
            return null;
        }
    }
 
    /** 수정(추가, 삭제)된 전화번호부를 저장하는 함수 */
    public void save() {
        if (modified) {         // 변경사항이 있다면
            try {
                PrintWriter out =
                    new PrintWriter(new FileWriter(sourceName));
                    // 파일을 열어 스트림을 생성
                 
                for (int i = 0; i < size; i++) {
                    if(theDirectory[i].getNumber() == null)
                        continue;
                    out.println(theDirectory[i].getName());
                    out.println(theDirectory[i].getNumber());
                }   // 기록한다.
                 
                out.close();            // 스트림을 닫는다.
                modified = false;       // 수정여부를 false로
            } catch (Exception ex) {
                System.err.println("Save of directory failed");
                ex.printStackTrace();
                System.exit(1);
            }
        }
    }
 
    /** 매개변수 name으로 저장된 연락처를 찾는 함수 */
    private int find(String name) {
        for (int i = 0; i < size; i++) {
            if (theDirectory[i].getName().equals(name)) {
                return i;   // 찾으면 i를 반환(i는 순서를 의미한다.)
            }
        }
        return -1// Name not found.(이름을 못 찾으면 -1을 반환)
    }
 
    /** 이름과 전화번호를 추가하는 함수 */
    private void add(String name, String number) {
        if (size >= capacity) {      // 현재 저장되어 있는 개수가 최대 저장 개수보다 크면
            reallocate();           // 저장 용량을 할당한다.(용량 증가)
        }
        theDirectory[size] = new DirectoryEntry(name, number); // 추가
        size++;     // 현재 저장 개수 증가
    }
 
    /** 용량이 가득찼을 경우 용량을 더 할당해주는 함수 */
    private void reallocate() {
        capacity *= 2;              // 최대 용량을 두배로 늘린다.
        DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
        // 임시 전화번호부 배열을 생성한다.
        System.arraycopy(theDirectory, 0, newDirectory, 0, theDirectory.length);
        // 기존 전화번호부 배열의 내용을 임시 전화번호부 배열에 복사한다.
        theDirectory = newDirectory;
        // 참조 변수(전화번호부 배열)에 용량이 증가된 임시 전화번호부 배열을 연결한다.
    }
 
    /** 연락처를 삭제하는 함수 */
    public void removeEntry(String name) {
        /**** EXERCISE ****/
        int index = find(name);
         
        if (index > -1) {
            theDirectory[index].setNumber(null);
            modified = true;
        }
    }
}

 
PDGUI.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package PD;
 
import javax.swing.JOptionPane;
 
/**
 * provides graphical user interface
 * GUI를 제공하는 클래스. */
 
public class PDGUI {
    private PhoneDirectory theDirectory = null;
 
    /** GUI를 표시하고, 전화번호부 기능을 수행하는 함수 */
    public void processCommands(PhoneDirectory thePhoneDirectory) {
        String[] commands = { "Add/Change Entry", "Look Up Entry",
                "Remove Entry", "Save Directory", "Exit" };
        theDirectory = thePhoneDirectory;   // 매개변수로 받아온 기능 수행 클래스를
                                            // 등록
        int choice;
         
        do {
            choice = JOptionPane.showOptionDialog(null, "Select a Command",
                    "PhoneDirectory", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, commands,
                    commands[commands.length - 1]);
            // 다이얼로그 GUI를 정의. 옵션 버튼의 인덱스를 반환한다.
             
            switch (choice) {       // 옵션 버튼의 인덱스에 따라 수행
            case 0:
                doAddChangeEntry();
                break;
            case 1:
                doLookupEntry();
                break;
            case 2:
                doRemoveEntry();
                break;
            case 3:
                doSave();
                break;
            case 4:
                doSave();
                break;
            }
        } while (choice < commands.length - 1);
        System.exit(0);
    }
 
    /** 연락처를 추가하거나 수정하는 함수 */
    private void doAddChangeEntry() {
        String newName = JOptionPane.showInputDialog("Enter name");
        // 간단한 input 다이얼로그를 생성
        if (newName == null) {
            return; // Dialog was cancelled.(입력되지 않으면 input 다이얼로그 파괴)
        }
        String newNumber = JOptionPane.showInputDialog("Enter number");
        if (newNumber == null) {
            return; // Dialog was cancelled.
        }
        String oldNumber = theDirectory.addOrChangeEntry(newName, newNumber);
        String message = null;
        if (oldNumber == null) { // New entry.
            message = newName + " was added to the directory"
                    + "\nNew number: " + newNumber;
        } else { // Changed entry.
            message = "Number for " + newName + " was changed "
                    + "\nOld number: " + oldNumber + "\nNew number: "
                    + newNumber;
        }
        JOptionPane.showMessageDialog(null, message);
    }
 
    /** 저장된 연락처를 보여주는 함수 */
    private void doLookupEntry() {
        // Request the name.
        String theName = JOptionPane.showInputDialog("Enter name");
        if (theName == null) {
            return; // Dialog was cancelled.
        }
        String theNumber = theDirectory.lookupEntry(theName);
        String message = null;
        if (theNumber != null) { // Name was found.
            message = "The number for " + theName + " is " + theNumber;
        } else { // Name was not found.
            message = theName + " is not listed in the directory";
        }
        JOptionPane.showMessageDialog(null, message);
    }
 
    /**
     * Method to remove an entry. pre: The directory has been loaded with data.
     * post: The requested name is removed, modified is set to true.
     */
     
    /** 저장된 연락처를 삭제하는 함수 */
    private void doRemoveEntry() {
        /**** EXERCISE ****/
        String theName = JOptionPane.showInputDialog("Enter name");
        if(theName == null){
            return;
        }
        String theNumber = theDirectory.lookupEntry(theName);
        String message = null;
        if(theNumber != null){
            message = theName + ", " + theNumber +
            " was deleted in the directory";
            theDirectory.removeEntry(theName);      // 삭제
        } else {
            message = theNumber + " is not listed in the directory";
        }
        JOptionPane.showMessageDialog(null, message);
    }
 
    /**
     * Method to save the directory to the data file. pre: The directory has
     * been loaded with data. post: The current contents of the directory have
     * been saved to the data file.
     */
    private void doSave() {
        theDirectory.save();
    }
}

 


 

728x90
반응형
:
Posted by mapagilove
728x90
반응형

안드로이드 - Android에서의 TCP/IP 통신


 

 

안드로이드 에뮬레이터와 데스크탑 서버간 TCP/IP통신을 하는 간단한 코드이다.
보통 이런 테스트는 loopback을 이용하면 되지 않을까? 라고 착각하는 사람들이 굉장히 많을 것이다. 
그래서 서버의 주소를 getLocalHost()를 통해 가져오게 되면 완전 삽질이다.
왜냐? 안드로이드 에뮬레이터의 localhost는 안드로이드 에뮬레이터의 네트웍이지 데스크탑의 네트웍이 아니기 때문이다. 따라서 아래의 소스코드는 일단 네트웍이 돌아가는 컴퓨터에서만 작동이 가능하다.

- Android Client의 메인부분

package android.SocketTest;
import android.app.Activity;
import android.os.Bundle;

public class SocketTest extends Activity {

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Thread cThread = new Thread(new TCPClient());
cThread.start();
}
}


- Client의 실제코드
package android.SocketTest;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.TCPDesktopServer.TCPDesktopServer;
import android.util.Log;

public class TCPClient implements Runnable {
public void run() {
try {
// 서버의 주소를 로컬호스트라고 127.0.0.1로 하는 삽질은 하지말것 -_-;
InetAddress serverAddr = InetAddress.getByName(TCPDesktopServer.SERVERIP);

Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 4444);

String message = "Hello from Client";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);

out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");

} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}

- 데스크탑 서버 코드
package android.TCPDesktopServer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPDesktopServer implements Runnable{
public static final int SERVERPORT = 4444;
public static final String SERVERIP = "192.168.0.16";

public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);

while (true) {
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");

try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("S: Received: '" + str + "'");
} catch(Exception e) {
System.out.println("S: Error");
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}

} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}

public static void main (String a[]) {
Thread desktopServerThread = new Thread(new TCPDesktopServer());
desktopServerThread.start();
}
}


 

728x90
반응형
:
Posted by mapagilove
728x90
반응형
안드로이드 - Tcp/ip를 통한 외부 DB데이터 처리

원본소스:http://www.devpia.com/Maeul/Contents/Detail.aspx?BoardID=7458&MAEULNO=911&no=54224&page=1

 

클라이언트 - 서버 - DB로 처리하는 방식입니다.

 

클라이언트

package com.net1;

import android.app.Activity;

import android.os.Bundle;

import android.view.*;

import android.widget.*;

public class MainApp extends Activity {

ListView lstView;

     

@Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        lstView = (ListView)findViewById(R.id.lstView);

    }

   

    public void chulbal(View v){

       //Toast.makeText(this, "시작", 2000).show();

       Connect connect = new Connect();

       connect.connect_server();

      

      if(v.getId() == R.id.btnCall){ //단순 서버 호출

             connect.send("good");      //호출

             String message = connect.read();   //반환값 얻기

             Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

      }else if(v.getId() == R.id.btnSelect){ //DB 자료 요청

             String[] items = connect.selectData();

             ListAdapter adapter = new ArrayAdapter<String>(this,

                        android.R.layout.simple_list_item_1, items);

             lstView.setAdapter(adapter);

       }

      

       connect.connect_close();

    }

}

 

 

Connect.java -----------

package com.net1;

import java.io.*;

import java.net.*;

import java.util.*;

import android.util.*;

public class Connect {

      private Socket socket;

      private BufferedReader in;

      private PrintWriter out;

 

      public void connect_server() {

            try {

                  socket = new Socket("xxx.xxx.xxx.xxx", 8888);

 

                  in = new BufferedReader(new InputStreamReader(socket

                             .getInputStream(), "UTF-8"));

 

                  out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true);

            } catch (Exception e) {

                  Log.i("disp", "connect_server err : " + e);

            }

      }

 

      public void send(String message) { // 메세지 전송(서버 호출)

            try {

                  out.println(message);

                  out.flush();

            } catch (Exception e) {

                  Log.i("disp", "send err : " + e);

            }

      }

 

      public String read() { // 메세지 수신(서버로부터)

            try {

                  String message = in.readLine();

                  return message;

            } catch (Exception e) {

                  Log.i("disp", "read err : " + e);

                  return "read err:" + e.getMessage();

            }

      }

 

      public void connect_close() {

            try {

                  in.close();

                  out.close();

                  socket.close();

            } catch (Exception e) {

            }

      }

 

      public String[] selectData() { // DB 자료 반환

            String[] items = null;

            try {

                  out.println("selectData"); // 서버에 DB 자료 요청

                  String result = in.readLine();

 

                  if (!result.equals("select_err")) {

                      StringTokenizer st = new StringTokenizer(result, "$");

                      Log.i("disp", "ssssss : " + st.countTokens());

                      items = new String[st.countTokens()];

                      for (int i = 0; i < items.length; i++) {

                          items[i] = st.nextToken();

                      }

                  }

            } catch (Exception e) {

                  Log.i("disp", "selectData err : " + e);

            }

            return items;

      }

}

 

selectData 는 서버에서 명령문으로 받아 특정 테이블에 데이터를 넘겨받는 방식으로

구성되어 있습니다.

sql문장 전체를 넘겨 서버에서 리턴값만 받는 방식으로 하셔도 됩니다.

 

테스트라 간단하게 구성하였습니다.

 

아래는 서버의 일부 반환 소스입니다.

      public void process(){  //db 자료 처리  클라이언트로 전달

            ArrayList<String> list = new ArrayList<String>();

            DbConnect dbConnect = new DbConnect();

            list = dbConnect.selectData();

           

            if(list.isEmpty()){

                  send("select_err");

            }else{

                  String data = "";

                  for(String s : list){

                        data += s + "$";                   }

                  send(data);

            }

      }

 

      public ArrayList<String> selectData(){

            ArrayList<String> list = new ArrayList<String>();

            String sql = "select a, b, c from test";

           

            try {

                  pstmt = conn.prepareStatement(sql);

                  rs = pstmt.executeQuery();

                 

                  while(rs.next()){

                        String data = rs.getString(1) + " " +

                             rs.getString(2) + " " + rs.getString(3);

                        list.add(data);

                  }

            } catch (Exception e) {

                  System.out.println("selectData 오류 : " + e);

            } finally{

                  try {

                        if(rs !=null) rs.close();

                        if(pstmt !=null) pstmt.close();

                  } catch (Exception e2) {}

            }

           

            return list;

      }

728x90
반응형
:
Posted by mapagilove
반응형