コマンド飛ばして処理させたいーServerClient編


#イントロ

BroadcastReceiverでコマンドを送れるが、
他のアプリとの通信どうやるの？ってのがあって。
ネットワークでやったほうが面倒くさくね？ってことでServerーClient編

<table>
<tr><td>Serverで待ち受け<br>(Serverボタンをクリック)</td><td>メッセージ送信<br>(Clientをクリック)<br>※別端末</td>
<tr><td>
<img width=200 src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/547467/31e9a59a-ea34-0ef0-36f6-23e387786c3d.png">
</td><td>
<img width=200 src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/547467/b4ec5f07-cb21-f2c4-3325-25240d5a79e3.png">
</td>
</tr></table>

#環境
Windows10(64bit)
Android11

#ソース
構成はこうなっています
いじるファイルは
AndroidManifest.xml
MainActivitiy.java
activity_main.xml
新規ファイル
Client.java
Server.java


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/547467/3f1c8616-aff0-d8f3-4d2a-0e7f73e2e12b.png)


```AndroidManifest.xml
（略）
    <!-- アプリでネットワーク オペレーションを行うには、マニフェストに次の権限を含める必要があります。 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/547467/f936c478-7759-2063-ee71-a6341a378e9c.png)



```activity_main.xml
<?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">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="IP"
        android:textSize="34sp"
        app:layout_constraintEnd_toStartOf="@+id/editTextTextMultiLine2"
        app:layout_constraintHorizontal_bias="0.511"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextTextMultiLine" />

    <Button
        android:id="@+id/button2"
        android:layout_width="230dp"
        android:layout_height="66dp"
        android:layout_marginTop="80dp"
        android:text="Client"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.171"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintHorizontal_bias="0.55"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="230dp"
        android:layout_height="66dp"
        android:layout_marginTop="16dp"
        android:text="Server"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.173"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="334dp"
        android:layout_height="55dp"
        android:layout_marginTop="4dp"
        android:text="TextView"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2" />

    <EditText
        android:id="@+id/editTextTextMultiLine"
        android:layout_width="325dp"
        android:layout_height="46dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:gravity="start|top"
        android:inputType="textMultiLine"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.458"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/editTextTextMultiLine2"
        android:layout_width="214dp"
        android:layout_height="54dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:gravity="start|top"
        android:inputType="textMultiLine"
        android:text="192.168.1.26"
        app:layout_constraintTop_toBottomOf="@+id/editTextTextMultiLine"
        tools:layout_editor_absoluteX="198dp" />

    <EditText
        android:id="@+id/editTextTextMultiLine3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:ems="10"
        android:gravity="start|top"
        android:inputType="textMultiLine"
        android:text="39675"
        app:layout_constraintTop_toBottomOf="@+id/editTextTextMultiLine2"
        tools:layout_editor_absoluteX="198dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Port"
        android:textSize="34sp"
        app:layout_constraintEnd_toStartOf="@+id/editTextTextMultiLine3"
        app:layout_constraintHorizontal_bias="0.55"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

```MainActivity.java

package com.example.testservice;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private String mIp;
    private int mPort;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView_2 = findViewById(R.id.editTextTextMultiLine2);
        TextView textView_3 = findViewById(R.id.editTextTextMultiLine3);

        mIp = textView_2.getText().toString();
        mPort = Integer.parseInt(textView_3.getText().toString());

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                test();
            }
        });

        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                test2();
            }
        });
    }

    private void test(){
        Server server = Server.getmInstance();
        // スレッド化しないと、NetworkOnMainThreadException というエラーが発生
        new Thread(new Runnable() {
            @Override
            public void run() {
                TextView textView = findViewById(R.id.textView);
                server.start(textView,mIp,mPort);
            }
        }).start();
    }

    private void test2(){
        Client client = Client.getmInstance();
        // スレッド化しないと、NetworkOnMainThreadException というエラーが発生
        new Thread(new Runnable() {
            @Override
            public void run() {
                TextView textView = findViewById(R.id.editTextTextMultiLine);
                client.start(textView,mIp,mPort);
            }
        }).start();
    }
}

```

```Server.java

package com.example.testservice;

import android.util.Log;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

class Server {
    private static String TAG = Server.class.getSimpleName();

    private static Server mInstance = new Server();

    public static  synchronized Server getmInstance(){
        return mInstance;
    }

    public static void start(TextView textView, String ip, int port) {
        // サーバーソケットを生成＆待機

        try {
            ServerSocket server = new ServerSocket();
            InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);
            server.bind(inetSocketAddress);
            Log.d(TAG, "ip:" + ip + ",port:" + port);

            while (true) {
                Socket socket = server.accept();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
                PrintWriter writer = new PrintWriter(
                        socket.getOutputStream(), true);

                Log.d(TAG, "accept..");
                String line = reader.readLine();
                if (line != null) {
                    Log.d(TAG, "line:" + line);
                    textView.setText(line);
                    if (line.equals("\\q")) {
                        break;
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}



```


```Client.java

package com.example.testservice;

import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

class Client {

    final String TAG = this.getClass().getSimpleName();
    private static Client mInstance = new Client();

    public static  synchronized Client getmInstance(){
        return mInstance;
    }

    public static void start(TextView textView,String ip, int port){
        // クライアントソケットを生成
        try {
            InetAddress IPAddress = InetAddress.getByName(ip);
            Socket socket = new Socket(IPAddress, port);
            PrintWriter writer = new PrintWriter(
                    socket.getOutputStream(), true);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));

            while (true) {
                String input = textView.getText().toString();
                writer.println(input);
                System.out.println("［Server］" + reader.readLine());
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


```



#参考
https://developer.android.com/training/basics/network-ops/connecting?hl=ja
https://nompor.com/2018/12/04/post-3742/
https://akira-watson.com/android/httpurlconnection-get.html
https://java-code.jp/261