Server

 

ChatService

...더보기
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
package com.example.myserver;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
 
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class ChatService extends Service {
    public ChatService() {
 
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        new ServerThread().start();
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
 
    class ServerThread extends Thread {
        @Override
        public void run() {
            //super.run();
 
            int port = 5001;
 
            try {
                ServerSocket server = new ServerSocket(port);
                Log.d("ServerThread""서버가 실행됨");
 
                while (true) {
                    Socket socket = server.accept();
 
                    ObjectInputStream instream = new ObjectInputStream(socket.getInputStream());
                    Object input = instream.readObject();
                    Log.d("ServerThread""input : " + input);
 
                    ObjectOutputStream outstream = new ObjectOutputStream(socket.getOutputStream());
                    outstream.writeObject(input + "from server.");
                    outstream.flush();
                    Log.d("ServerThread""output 보냄" + input);
 
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
 
cs

 

MainActivity

...더보기
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
package com.example.myserver;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
 
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //new ServerThread().start();
 
                Intent intent = new Intent(getApplicationContext(), ChatService.class);
                startService(intent);
            }
        });
 
    }
 
    /*class ServerThread extends Thread {
        @Override
        public void run() {
            //super.run();
 
            int port = 5001;
 
            try {
                ServerSocket server = new ServerSocket(port);
                Log.d("ServerThread", "서버가 실행됨");
 
                while (true) {
                    Socket socket = server.accept();
 
                    ObjectInputStream instream = new ObjectInputStream(socket.getInputStream());
                    Object input = instream.readObject();
                    Log.d("ServerThread", "input : " + input);
 
                    ObjectOutputStream outstream = new ObjectOutputStream(socket.getOutputStream());
                    outstream.writeObject(input + "from server.");
                    outstream.flush();
                    Log.d("ServerThread", "output 보냄" + input);
 
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
 
 
        }
    }*/
}
 
cs

 

activity_main.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" 서버 시작"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
cs

 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Client

 

MainActivity

...더보기
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
package com.example.boostcoursepractice;
 
import android.os.AsyncTask;
import android.os.Bundle;
 
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
 
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
 
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
 
import android.view.MenuItem;
 
import com.google.android.material.navigation.NavigationView;
 
import androidx.drawerlayout.widget.DrawerLayout;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
 
import android.view.Menu;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
 
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
 
public class MainActivity extends AppCompatActivity {
 
    Button button;
    TextView textView ;
    Handler handler ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        handler = new Handler() ;
        textView = (TextView) findViewById(R.id.textView) ;
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new ClientThread().start();
            }
        });
    }
 
    class ClientThread extends Thread {
 
        @Override
        public void run() {
            //super.run();
            String host = "localhost";
            int port = 5001;
 
            try {
                Socket socket = new Socket(host, port);
 
                ObjectOutputStream outstream = new ObjectOutputStream(socket.getOutputStream());
                outstream.writeObject("안녕!");
                outstream.flush();
                Log.d("ClientThread""서버로 보냄.");
 
                ObjectInputStream instream  = new ObjectInputStream(socket.getInputStream());
                final Object input = instream.readObject() ;
                Log.d("ClientThread""받은 데이터 : " + input);
 
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("받은 데이터 : " + input);
                    }
                }) ;
 
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
 
        }
    }
 
}
 
 
 
 
 
cs

 

activity_main.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="받은 데이터 :"
        android:textSize="24dp" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="클라이언트 시작" />
</LinearLayout>
 
cs

 

소켓프로그래밍은 우선 클라이언트가 요청하고 그 요청에 응답하여 서버가 응답을 보내면서 이루어 진다.

서버는 ip를 가지고 있고 포트번호를 가지고 있다. 이에 대해 클라이언트가 서버의 ip와 포트번호를 이용하여 요청을 보내면서 네트워크 통신은 이루어진다. 

 

위 첨부해놓은 코드처럼 보면 클라이언트는 보내기 -> 받기 순이고 서버는 받기->보내기 순이다. 

 

이 예제에서는 또한 서버쪽에서 어플리케이션이 종료 되어도 계속 서버의 기능을 할 수 있도록 서비스를 이용해 구현해 놓았다. 

 

 

 

서버 결과화면

 

클라이언트 결과화면

+ Recent posts