마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

socket 통신 연결이 안됩니다 ㅠ

0 추천
package atifsoftwares.blogspot.led_lamp;


import android.os.Bundle;
import android.os.AsyncTask;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.net.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Scanner;
import com.skydoves.colorpickerpreference.ColorListener;
import com.skydoves.colorpickerpreference.ColorEnvelope;
import com.skydoves.colorpickerpreference.ColorPickerView;
import java.io.IOException;
import static android.widget.Toast.LENGTH_SHORT;



public class MainActivity extends AppCompatActivity {

    TextView textView;
    private EditText edit_ip1, edit_ip2, edit_ip3, edit_ip4, edit_port;
    private Button btn_connect;
    private String temp_ip;
    private String temp_port;
    int[] RGBcolor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final ProtocolTask protocol_task = new ProtocolTask();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit_ip1 = findViewById(R.id.edit_1);
        edit_ip2 = findViewById(R.id.edit_2);
        edit_ip3 = findViewById(R.id.edit_3);
        edit_ip4 =  findViewById(R.id.edit_4);
        edit_port =  findViewById(R.id.edit_port);

        btn_connect = findViewById(R.id.CONNECT);
        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    temp_ip = edit_ip1.getText().toString() + "." + edit_ip2.getText().toString() + "." + edit_ip3.getText().toString() + "." + edit_ip4.getText().toString();
                    temp_port = edit_port.getText().toString();
                    Toast.makeText(getApplicationContext(),temp_ip + '/' + temp_port, LENGTH_SHORT).show();
                    protocol_task.execute();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), temp_ip + "/connecting failed", LENGTH_SHORT).show();

                }
            }
        });//end button(CONNECT)

        textView = findViewById((R.id.textView1));

        ColorPickerView colorPickerView = (ColorPickerView) findViewById(R.id.colorPickerView);
        colorPickerView.setColorListener(new ColorListener() {

            @Override
            public void onColorSelected(ColorEnvelope colorEnvelope) {
                textView.setBackgroundColor(colorEnvelope.getColor());
                RGBcolor = colorEnvelope.getColorRGB();
                textView.setText("R : " + RGBcolor[0] + "          G :" + RGBcolor[1] + "         B : " + RGBcolor[2]);
                new Thread() {
                    public void run() {
                        try {
                            protocol_task.send(RGBcolor);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });//end colorselect


    }//end oncreate

    @Override
    public void onBackPressed() {
        android.os.Process.killProcess(Process.myPid());
        super.onBackPressed();
    }

    public class AsyncProgressUpdateType {
        final static int SOCKET_CONNECTING = 1;
        final static int SOCKET_CONNECTED = 2;
        final static int SOCKET_FAIL = 3;
        final static int SOCKET_EXIT = 4;
    }

    class ProtocolTask extends AsyncTask<Void, Integer, Void> {
        Socket socket;
        Scanner in = new Scanner((System.in));
        private DataOutputStream write_stream;
        private DataInputStream read_stream;

        ByteBuffer recv_buffer = ByteBuffer.allocate(12);
        ByteBuffer send_buffer = ByteBuffer.allocate(12);

        @Override
        protected Void doInBackground(Void... voids) {
            publishProgress(AsyncProgressUpdateType.SOCKET_CONNECTING);
            int read_byte;
            int port = Integer.parseInt(temp_port);

            try {
                socket = new Socket(temp_ip, port);
                write_stream = new DataOutputStream(socket.getOutputStream());
                read_stream = new DataInputStream(socket.getInputStream());
                publishProgress(AsyncProgressUpdateType.SOCKET_CONNECTED);
            } catch (Exception e) {
                publishProgress(AsyncProgressUpdateType.SOCKET_FAIL);
            }
            recv_buffer.order(ByteOrder.LITTLE_ENDIAN);
            send_buffer.order(ByteOrder.LITTLE_ENDIAN);

            while (true) {
                try {
                    read_byte = read_stream.read(recv_buffer.array(), 0, recv_buffer.capacity());
                    if (read_byte == -1)
                        break;
                }
                catch (Exception e) {
                }
            }
            try {
                publishProgress(AsyncProgressUpdateType.SOCKET_EXIT);
                socket.close();
            } catch (IOException e) {
            }
            return null;
        }

        protected void onProgressUpdate(Integer... params) {
            if (params[0] == AsyncProgressUpdateType.SOCKET_CONNECTING)
                Toast.makeText(getApplicationContext(), "connecting..", LENGTH_SHORT).show();
            else if (params[0] == AsyncProgressUpdateType.SOCKET_CONNECTED)
                Toast.makeText(getApplicationContext(), "connect success!", LENGTH_SHORT).show();
            else if (params[0] == AsyncProgressUpdateType.SOCKET_FAIL)
                Toast.makeText(getApplicationContext(), "connect fail!", LENGTH_SHORT).show();
            else if (params[0] == AsyncProgressUpdateType.SOCKET_EXIT)
                Toast.makeText(getApplicationContext(), "connect end!", LENGTH_SHORT).show();
        }

        public void send(int[] color) throws IOException{
            try {
                if (socket.isConnected()) {

                    for (int i = 0; i < 3; i++) {
                        write_stream.write(color[i]);
                    }
                }
            }
            catch (IOException e) {
            }
            catch (Exception e) {
                Log.d("실패", "실패");
                e.printStackTrace();
            }
        }
    }
}
졸작해야되는데 (120 포인트) 님이 5월 14일 질문

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...