티스토리 뷰

안드로이드 Socket 네트워크 사용 방법
: 안드로이드 4.0 이상부터는 Thread를 사용해야만 통신이 가능하다. java Thread 또는 AsyncTask 둘중 하나를 사용해야 한다.

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
public class MainActivity extends AppCompatActivity implements  Runnable{
 
    Socket                  sock;
    DataOutputStream        output;
    DataInputStream         input;
 
    int                     PORT = 1040;
    String                  IP = "xxx.xxx.xxx.xxx";
 
    Thread                  t = new Thread(this);
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t.start();
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
 
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
 
        return super.onOptionsItemSelected(item);
    }
 
    @Override
    public void run()
    {
        try
        {
            sock            = new Socket(IP, PORT);
            output          = new DataOutputStream(sock.getOutputStream());
            input           = new DataInputStream(sock.getInputStream());
        }
        catch( Exception e )
        {
            Toast.makeText(this"서버 연결이 안됨", Toast.LENGTH_SHORT).show();
        }
    }
}

cs


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
public void run()
{
    // 서버연결
    try
    {
        sock            = new Socket(IP, PORT);
        output          = new DataOutputStream(sock.getOutputStream());
        input           = new DataInputStream(sock.getInputStream());
    }
    catch( Exception e )
    {
        Toast.makeText(this"서버 연결이 안됨", Toast.LENGTH_SHORT).show();
    }
 
    try
    {
        output.write("test");
 
        while (true)
        {
            byte[] data = new byte[255];
            input.read(data);
            String str = new String(data);
            Log.d("testInput", str);
        }
    }
    catch (IOException e)
    {
 
    }
}
cs

위의 방법을 사용하게 되면 소켓 연결을 끊어야 write로 서버로 데이터가 전송 된다. write를 한 다음 write한 명령어에 따른 값을 바로 read 할 수 없음.

서버 연결이 된 상태에서 데이터를 보내고 받는 다른 방법
    : 아래와 같이 작성하면 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sock          = new Socket(IP, PORT);
input         = new BufferedReader( new InputStreamReader( sock.getInputStream() ) );
output       = new PrintWriter( new OutputStreamWriter( sock.getOutputStream() ) );
 
/**
 *  GET_RESULT 메시지를 보낸다음, 서버로부터 결과를 받는다.*/
 try
 {
     output.println("GET_RESULT");
     output.flush();
 
     String read = input.readLine();
 }
 catch (IOException e)
     e.printStackTrace();
cs
:
퍼미션 설정
AndroidManifest.xml -> <uses-permission android:name="android.permission.INTERNET"/>  추가


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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
글 보관함