반응형

휴대폰과 라즈베리파이간의 소켓통신을 해보자

이렇게 통신할수 있다면 밖에서도 다양한 집안의 다양한 일들을 시킬수 있다.

소켓통신으로 휴대폰->라즈베리파이로 명령을 보내면 블루투스로 라즈베리파이->아두이노로 명령을 보내 불켜기 등 다양한 일들을 직접가지않고도 휴대폰으로 제어할수있게 될것이다.

소켓통신이란?

https://recipes4dev.tistory.com/153

자바의 소켓통신

https://recipes4dev.tistory.com/164?category=789384

 

서버는 라즈베리파이이고 안드로이드를 클라이언트로 구현하면 된다.

간단하게 에코서버를 구현하였고 휴대폰에서 입력하여 전송하면 서버에서 받은 데이터를 다시 전송해주어 휴대폰에 출력되도록 만들었다. 

 

 

서버구현

SocketServer.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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
 
 
public class SocketServer implements Runnable {
    public static final int ServerPort = 9999;
    @Override
    public void run() {
        try {
            
            ServerSocket serverSocket = new ServerSocket(ServerPort);//소켓생성
            System.out.println("Connecting...");
            while (true) {
                //client 접속 대기
                Socket client = serverSocket.accept(); //데이터 전송 감지
                System.out.println("Receiving...");
                try {
 
                    //client data 수신
                    
                    //소켓에서 넘오는 stream 형태의 문자를 얻은 후 읽어 들어서  bufferstream 형태로 in 에 저장.                                                                                           
                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    //in에 저장된 데이터를 String 형태로 변환 후 읽어들어서 String에 저장
                    String str = in.readLine();
                    System.out.println("Received: '" + str + "'");
                    //client에 다시 전송
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
                    out.println("Server Received : '" + str + "'");
 
                } catch (Exception e) {//데이터 전송과정에서의 에러출력
                    System.out.println("Error");
                    e.printStackTrace();
                } finally {//소켓 연결 종료
                    client.close();
                    System.out.println("Done.");
                }
            }
 
        } catch (Exception e) {//연결 과정에서의 에러출력
            System.out.println("S: Error");
            e.printStackTrace();
        }
 
    }
 
    public static void main(String[] args) {
 
        Thread ServerThread = new Thread(new SocketServer());//Thread로 실행
        ServerThread.start();//서버 실행
 
    }
 
}
 
cs

 

 

 

클라이언트 구현(안드로이드)

 

.xml(디자인)

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
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp"
        android:weightSum="5">
 
        <LinearLayout
            android:layout_weight="0.5"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:orientation="horizontal"
            android:weightSum="5"
            >
 
            <EditText
                android:id="@+id/EditText01"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="4"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.874"
                app:layout_constraintStart_toStartOf="@+id/Button01"
                tools:layout_editor_absoluteY="608dp" />
 
            <Button
                android:id="@+id/Button01"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="Send"
                app:layout_constraintBottom_toBottomOf="parent"
                tools:layout_editor_absoluteX="317dp" />
 
        </LinearLayout>
 
        <TextView
            android:id="@+id/chatTV"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="9.5"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent" />
    </LinearLayout>
 
</android.support.constraint.ConstraintLayout>
 
cs

 

 

.java

패키지명과 서버IP,PORT를 수정해준다.

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
package com.example.client;    //만든 패키지 명에 따라 바꾸어 주어야한다.
 
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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.InetAddress;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
    private Handler mHandler;
    Socket socket;
    private String ip = "1.1.1.1"// 서버의 IP 주소
    private int port = 9999// PORT번호를 꼭 맞추어 주어야한다.
    EditText et;
    TextView msgTV;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler();
        et = (EditText) findViewById(R.id.EditText01);
        Button btn = (Button) findViewById(R.id.Button01);
        msgTV = (TextView)findViewById(R.id.chatTV);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (et.getText().toString() != null || !et.getText().toString().equals("")) {
                    ConnectThread th =new ConnectThread();
                    th.start();
                }
            }
        });
    }
    @Override
    protected void onStop() {
        super.onStop();
        try {
            socket.close();//종료시 소켓도 닫아주어야한다.
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    class ConnectThread extends Thread{//소켓통신을 위한 스레드
        public void run(){
            try{
                //소켓 생성
                InetAddress serverAddr = InetAddress.getByName(ip);
                socket =  new Socket(serverAddr,port);
                //입력 메시지
                String sndMsg = et.getText().toString();
                Log.d("=============", sndMsg);
                //데이터 전송
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                out.println(sndMsg);
                //데이터 수신
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String read = input.readLine();
                //화면 출력
                mHandler.post(new msgUpdate(read));
                Log.d("=============", read);
                socket.close();//사용이 끝난뒤 꼭 닫아주어야한다.
            }catch(Exception e){
                e.printStackTrace();
            }
        }
 
 
    }
    // 받은 메시지 출력
    class msgUpdate implements Runnable {
        private String msg;
        public msgUpdate(String str) {
            this.msg = str;
        }
        public void run() {
            msgTV.setText(msgTV.getText().toString() + msg + "\n");
        }
    };
}
 
 
cs

 

 

 

Manifest.xml(인터넷 사용권한 추가)

 

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

 

 

 

내 휴대폰에서 설치하고 확인해보기

https://m.blog.naver.com/PostView.nhn?blogId=beaqon&logNo=221076390196&proxyReferer=https:%2F%2Fwww.google.com%2F

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기