如何通过按钮检查哪个ip连接?

时间:2015-07-31 06:28:22

标签: java android networking android-studio

MainActivity.java 上,我有一个与服务器连接的方法:

private byte[] Get(String urlIn)
    {
        URL url = null;
        String urlStr = urlIn;

        if (urlIn!=null)
            urlStr=urlIn;

        try
        {
            url = new URL(urlStr);
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
            return null;
        }
        HttpURLConnection urlConnection = null;
        try
        {

            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            byte[] buf=new byte[10*1024];
            int szRead = in.read(buf);
            byte[] bufOut;

            if (szRead==10*1024)
            {
                throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
            }
            else
            {
                bufOut = Arrays.copyOf(buf, szRead);
            }

            return bufOut;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        finally
        {
            if (urlConnection!=null)
                urlConnection.disconnect();
        }
    }

我从onTouchEvent()调用此方法:

@Override
        public boolean onTouchEvent(MotionEvent event)
        {
            float eventX = event.getX();
            float eventY = event.getY();

            float lastdownx = 0;
            float lastdowny = 0;

            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(eventX, eventY);
                    circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
                    lastdownx = eventX;
                    lastdowny = eventY;

                    Thread t = new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            byte[] response = null;
                            if (is_start == true)
                            {
                                response = Get("http://10.0.0.2:8098/?cmd=start");
                                is_start = false;
                            }
                            else
                            {
                               response = Get("http://10.0.0.2:8098/?cmd=stop");
                                is_start = true;
                            }

                            if (response!=null)
                            {
                                String a = null;
                                try
                                {
                                    a = new String(response,"UTF-8");
                                    textforthespeacch = a;
                                    MainActivity.currentActivity.initTTS();
                                } catch (UnsupportedEncodingException e)
                                {
                                    e.printStackTrace();
                                }
                                Logger.getLogger("MainActivity(inside thread)").info(a);
                            }
                        }
                    });
                    t.start();

                    return true;
                case MotionEvent.ACTION_MOVE:
                    path.lineTo(eventX, eventY);
                    break;
                case MotionEvent.ACTION_UP:
                    circlePath.reset();

                    break;
                default:
                    return false;
            }
            invalidate();
            return true;
        }

所以现在我连接到10.0.0.2:8098 但是,当我在我的电脑室的网络上连接我的Android设备时。

但是如果我搬到起居室并连接到网络那里有一个不同的网络与另一台PC,在这种情况下,pc ip是不同的:10.0.0.3:8099

所以我在MainActivity.java中添加了一个按钮点击事件:

public class MainActivity extends ActionBarActivity
{
    private static final int MY_DATA_CHECK_CODE = 0;
    public static MainActivity currentActivity;
    TextToSpeech mTts;
    private String targetURL;
    private String urlParameters;
    private Button btnClick;
    private String clicking = "clicked";

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

        addListenerOnButton();

        currentActivity = this;

        initTTS();


    }

    public void addListenerOnButton() {

        btnClick = (Button) findViewById(R.id.checkipbutton);

        btnClick.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {

            }

        });

    }

如果pc ip是 10.0.0.3:8099或10.0.0.2:8098

,我想在用wifi连接到网络后检查按钮点击事件

我需要它会尝试连接到这个服务器,如果成功则设置为全局变量全局字符串ip。

我添加了一个全局变量:string ipaddress 现在我在我的代码中使用静态地址,但我需要检查哪个IP地址是正确的,然后将此ip设置为我稍后将在我的代码中用作IP地址的变量。

如何在按钮点击事件中进行检查?

这就是我现在尝试的:

在我的MainActivity顶部,我添加了:

private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
Socket socket = null;

然后在onCreate:

ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;
addListenerOnButton();
new Thread(new ClientThread()).start();

然后

public void addListenerOnButton() {

        btnClick = (Button) findViewById(R.id.checkipbutton);

        btnClick.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {

                    try {

                        String str = btnClick.getText().toString();
                        PrintWriter out = new PrintWriter(new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream())),
                                true);
                        out.println(str);
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


            }


        });

    }

和ClientThread

class ClientThread implements Runnable {

        @Override
        public void run() {
            for (int i=0; i<ipaddresses.length; i++)
            {
                try
                {
                    InetAddress serverAddr = InetAddress.getByName(ipaddresses[i]);

                    socket = new Socket(serverAddr, ipports[i]);

                } catch (UnknownHostException e1)
                {
                    e1.printStackTrace();
                } catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }

    }

这是我得到的异常消息的屏幕截图:

Exception

例外是在线:

new OutputStreamWriter(socket.getOutputStream())),

1 个答案:

答案 0 :(得分:0)

您必须打开套接字才能检查服务器连接。以下是您在点击事件中向服务器发送字符串的示例:

LayerDrawable drawable = (LayerDrawable) getProgressDrawable();
Drawable progress = drawable.getDrawable(2);
DrawableCompat.setTint(progress, getResources().getColor(COLOR1));
progress = drawable.getDrawable(1);
DrawableCompat.setTintMode(progress, PorterDuff.Mode.DST_ATOP);
DrawableCompat.setTint(progress, getResources().getColor(COLOR1));
DrawableCompat.setTintMode(progress, PorterDuff.Mode.SRC_ATOP);
DrawableCompat.setTint(progress, getResources().getColor(COLOR2));
progress = drawable.getDrawable(0);
DrawableCompat.setTint(progress, getResources().getColor(COLOR2));

}

因此,如果您尝试连接服务器时遇到异常,则表示您无法连接。