2000ms后无法连接到/192.168.1.**(端口****)

时间:2013-06-15 05:22:46

标签: android sockets baseadapter

我是android新手。我在android中使用Socket。我在下面写了这些代码, 但它在连接服务器时会出现异常,

06-15 04:48:34.615:V / tcpserver(801):2000ms后无法连接到/192.168.1.**(端口 * *)

我如何处理这些?任何建议, 提前致谢

      public class GridAdapter extends BaseAdapter {
private Context context;
private String id[];
private String cmd[];
private String btnTextureA[];
private int size;
HttpHelper httpHelper;
String res;
Handler mHandler;
Runnable mRun;
TextView[] tvS = new TextView[]{};
Database db;
Cursor cursor;
String dap1;
String ip_address;
String port;int portInt;
String server;
String positionIs;
String idforevent;
Socket socket;
// constructor.
public GridAdapter(Context context, String[] id, String[] cmd,
        String[] btnTextureA, int size, String id2) {
    this.context = context;
    this.id = id;
    this.cmd = cmd;
    httpHelper = new HttpHelper(context);
    res = new String();
    mHandler = new Handler();
    this.btnTextureA = btnTextureA;
    this.idforevent=id2;
    tvS = new TextView[id.length];
    db = new Database(context);
    db.getSqliteDatabase();

}

public View getView(final int position, View convertView, ViewGroup parent) {

    // create new image view to bind in the grid.

    Log.e("inTexture", btnTextureA[position]);
    if (btnTextureA[position].contains("RED")
            || btnTextureA[position].contains("GREEN")) {
        FrameLayout fl = new FrameLayout(context);
        fl.setLayoutParams(new GridView.LayoutParams(
                ((Global.width / 2) - Global.padding * 2),
                Global.height / 10));
        Button iv = new Button(context);
        //tvS[position].setId(position+1+3000);

        // set parameters.
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ((Global.width / 2) - Global.padding * 2),
                Global.height / 10);
        iv.setLayoutParams(params);
        iv.setTextColor(Color.BLACK);
        iv.setGravity(Gravity.LEFT);
        Log.e("GetView", "" + position);
        iv.setTag(cmd[position]);
        iv.setTextSize(15);
        iv.setId(position + 1);
        iv.setBackgroundResource(R.drawable.list_selector);
        iv.setText(id[position]);
        Log.i("UI", "id at position"+id[position]);
        iv.setPadding(Global.padding, Global.padding, Global.padding,
                Global.padding);
        mRun = new Runnable() {

            @Override
            public void run() {
                Toast.makeText(context, "Response: " + res,
                        Toast.LENGTH_LONG).show();

            }
        };
        iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {

        Toast.makeText(context, "Your position is "+position, Toast.LENGTH_LONG).show();
        positionIs=String.valueOf(position+1);

        Log.i("UI", "pos is "+positionIs+"value will be"+idforevent);

        cursor = db.getCONFIGValForButton("A",idforevent,positionIs);
        cursor.moveToFirst();
        dap1 =(cursor.getString(cursor.getColumnIndex(Database.CONFIG_DAP1)));

        Log.i("UI", "dap1 value is "+dap1);

        cursor=db.getANAValforIpPort("SRV",dap1);
        cursor.moveToFirst();
        ip_address =(cursor.getString(cursor.getColumnIndex(Database.ANA_P1)));

        Log.i("UI", "IP value is "+ip_address);

        port =(cursor.getString(cursor.getColumnIndex(Database.ANA_P2)));

        Log.i("UI", "port value is "+port);

        server =(cursor.getString(cursor.getColumnIndex(Database.ANA_P3)));
        portInt=Integer.parseInt(port);



                Thread t1 = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        /*res = httpHelper.connectToHttp(v.getTag()
                                .toString());
                        mHandler.post(mRun);*/
                        startConnection(ip_address,portInt);
                    }
                });
                t1.start();
            }
        });

        final TextView tv = new TextView(context);
        FrameLayout.LayoutParams paramTv = new FrameLayout.LayoutParams(30,30);
        paramTv.gravity = Gravity.RIGHT|Gravity.TOP;
        tv.setLayoutParams(paramTv);
        tv.setTextColor(Color.BLACK);
        tv.setText("0");
        tv.setPadding(5, 5, 5, 5);
        //tvS[position] = tv; 
        //tvS[position].setId(position+1+3000);

        SeekBar pb = new SeekBar(context);
        FrameLayout.LayoutParams paramBar = new FrameLayout.LayoutParams((Global.width / 2) - Global.padding * 8,30);
        paramBar.gravity = Gravity.RIGHT|Gravity.BOTTOM;
        pb.setLayoutParams(paramBar);
        pb.setId(position+1+5000);
        pb.setProgressDrawable(context.getResources().getDrawable(R.drawable.scrubber_progress_horizontal_holo_dark));
        //pb.setThumb(null);
        pb.setClickable(false);
        pb.setEnabled(false);
        pb.setProgress(10);
        pb.setMax(10);
        pb.setPadding(20, 0, 20, 0);
        pb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(context, seekBar.getProgress()+"", 100).show();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
            }
        });
        fl.addView(iv);
        fl.addView(pb);
        return fl;
    } else if (btnTextureA[position].contains("SLIDER")) {
        FrameLayout fl = new FrameLayout(context);
        fl.setLayoutParams(new GridView.LayoutParams(
                ((Global.width / 2) - Global.padding * 2),
                Global.height / 10));
        Button iv = new Button(context);
        //tvS[position].setId(position+1+3000);

        // set parameters.
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ((Global.width / 2) - Global.padding * 2),
                Global.height / 10);
        iv.setLayoutParams(params);
        iv.setTextColor(Color.BLACK);
        iv.setGravity(Gravity.LEFT);
        Log.e("GetView", "" + position);
        iv.setTag(cmd[position]);
        iv.setTextSize(15);
        iv.setId(position + 1);
        iv.setBackgroundResource(R.drawable.list_selector);
        iv.setText(id[position]);
        iv.setPadding(Global.padding, Global.padding, Global.padding,
                Global.padding);
        mRun = new Runnable() {

            @Override
            public void run() {
                Toast.makeText(context, "Response: " + res,
                        Toast.LENGTH_LONG).show();

            }
        };
        iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {

            Toast.makeText(context, "Your position is "+position, Toast.LENGTH_LONG).show();

            positionIs=String.valueOf(position+1);

            Log.i("UI", "pos is "+positionIs+"value will be"+idforevent);

            cursor = db.getCONFIGValForButton("A", idforevent,positionIs);
            cursor.moveToFirst();
            dap1 =(cursor.getString(cursor.getColumnIndex(Database.CONFIG_DAP1)));

            Log.i("UI", "dap1 value is "+dap1);

            cursor=db.getANAValforIpPort("SRV",dap1);
            cursor.moveToFirst();
            ip_address =(cursor.getString(cursor.getColumnIndex(Database.ANA_P1)));

            Log.i("UI", "IP value is "+ip_address);

            port =(cursor.getString(cursor.getColumnIndex(Database.ANA_P2)));

            Log.i("UI", "port value is "+port);

            server =(cursor.getString(cursor.getColumnIndex(Database.ANA_P3)));

            Log.i("UI", "server value is "+server);


            portInt=Integer.parseInt(port);

            Log.i("UI", "cursor called");


                //cursor = db.getCONFIGVal(mainBtn, id,"0");
                Thread t1 = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        startConnection(ip_address,portInt);
                        /*res = httpHelper.connectToHttp(v.getTag()
                                .toString());
                        mHandler.post(mRun);*/
                    }
                });
                t1.start();
            }
        });

        final TextView tv = new TextView(context);
        FrameLayout.LayoutParams paramTv = new FrameLayout.LayoutParams(30,30);
        paramTv.gravity = Gravity.RIGHT|Gravity.TOP;
        tv.setLayoutParams(paramTv);
        tv.setTextColor(Color.BLACK);
        tv.setText("0");
        tv.setPadding(5, 5, 5, 5);
        //tvS[position] = tv; 
        //tvS[position].setId(position+1+3000);

        SeekBar pb = new SeekBar(context);
        FrameLayout.LayoutParams paramBar = new FrameLayout.LayoutParams((Global.width / 2) - Global.padding * 8,30);
        paramBar.gravity = Gravity.RIGHT|Gravity.BOTTOM;
        pb.setLayoutParams(paramBar);
        pb.setId(position+1+5000);
        pb.setProgressDrawable(context.getResources().getDrawable(
                R.drawable.scrubber_progress_horizontal_holo_dark));
        pb.setThumb(context.getResources().getDrawable(R.drawable.scrubber_control_selector_holo));
        pb.setMax(10);
        pb.setPadding(20, 0, 20, 0);
        pb.setThumbOffset(0);
        pb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(context, seekBar.getProgress()+"", 100).show();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
            }
        });
        fl.addView(iv);
        fl.addView(pb);
        return fl;
    } else {
        Button iv;
        iv = new Button(context);

        // set parameters.
        AbsListView.LayoutParams params = new GridView.LayoutParams(
                ((Global.width / 2) - Global.padding * 2),
                Global.height / 10);
        iv.setLayoutParams(params);
        iv.setTextColor(Color.BLACK);
        iv.setGravity(Gravity.LEFT);
        Log.e("GetView", "" + position);
        iv.setTag(cmd[position]);
        iv.setTextSize(15);
        iv.setId(position + 1);
        iv.setBackgroundResource(R.drawable.list_selector);
        iv.setText(id[position]);
        iv.setPadding(Global.padding, Global.padding, Global.padding,
                Global.padding);
        mRun = new Runnable() {

            @Override
            public void run() {
                Toast.makeText(context, "Response: " + res,
                        Toast.LENGTH_LONG).show();

            }
        };
        iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {

        Toast.makeText(context, "Your position is "+position, Toast.LENGTH_LONG).show();

        positionIs=String.valueOf(position+1);

        Log.i("UI", "pos is "+positionIs+"value will be"+idforevent);

        cursor = db.getCONFIGValForButton("A", idforevent,positionIs);
        cursor.moveToFirst();
        dap1 =(cursor.getString(cursor.getColumnIndex(Database.CONFIG_DAP1)));

        Log.i("UI", "dap1 value is "+dap1);

        cursor=db.getANAValforIpPort("SRV",dap1);
        cursor.moveToFirst();
        ip_address =(cursor.getString(cursor.getColumnIndex(Database.ANA_P1)));

        Log.i("UI", "IP value is "+ip_address);

        port =(cursor.getString(cursor.getColumnIndex(Database.ANA_P2)));

        Log.i("UI", "port value is "+port);

        server =(cursor.getString(cursor.getColumnIndex(Database.ANA_P3)));

        Log.i("UI", "server value is "+server);

        portInt=Integer.parseInt(port);

        Log.i("UI", "cursor called");



                Thread t1 = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        /*res = httpHelper.connectToHttp(v.getTag()
                                .toString());
                        mHandler.post(mRun);*/
                        startConnection(ip_address,portInt);
                    }
                });
                t1.start();
            }
        });
        return iv;
    }

}

public void startConnection(String ip_address2, int portInt2) {




        //SocketAddress remoteAddr=new InetSocketAddress(ip_address2,portInt2);
try{
    socket=new Socket();
    Log.i("UI", "values are "+ip_address2+","+portInt2+"socket port;"+socket.getInetAddress());

    SocketAddress remoteAddr=new InetSocketAddress(ip_address2,portInt2);
    socket.connect(remoteAddr,2000);

    if(socket.isConnected()){
        Log.i("UI", "Socket is connected at ip"+ip_address2);




    }
    else
        Log.i("UI", "Socket is Disconnected at ip"+ip_address2);
}
catch(IOException e){
    socket=new Socket();
        Log.v("tcpserver", e.getMessage());
}

}

@Override
public int getCount() {
    return id.length;
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

}

1 个答案:

答案 0 :(得分:0)

尝试使用InetAddress,将其更改为:

 try{
     socket=new Socket();
     Log.i("UI", "values are "+ip_address2+","+portInt2+"socket port;"+socket.getInetAddress());

     InetAddress addr = InetAddress.getByName(ip_address2);
     SocketAddress remoteAddr = new InetSocketAddress(addr, portInt2);
     // Allow some more time to timeout, 10-15 seconds
     // if it is on the same network it may works, but if it is in the internet may be not.
     socket.connect(remoteAddr, 12000);

     if(socket.isConnected()){
         Log.i("UI", "Socket is connected at ip"+ip_address2);
     }
     else
         Log.i("UI", "Socket is Disconnected at ip"+ip_address2);
 }
 catch(IOException e){
     socket=new Socket();
         Log.v("tcpserver", e.getMessage());
 }