如何在整个程序中启用我的Socket并通过它传递值

时间:2018-07-19 07:40:43

标签: java android sockets android-studio tcpclient

这里我创建了一个套接字,我想使其成为全局的,并通过单击按钮将整数值传递给该套接字。但是当我尝试使Socket成为全局时,我却报错。通过它的整数值。如何使Socket全局并传递整数值。如何使Socket全局并传递整数值。

主要活动:

public class MainActivity extends AppCompatActivity {
Button buttonOn;
Button button1;

Socket socket;



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

    buttonOn = (Button) findViewById(R.id.ON);
    button1 = (Button) findViewById(R.id.button1);

    try {
        System.out.println("HIIIII");
        socket = new Socket("198.168.0.79",8888);
        socket.getKeepAlive();
    } catch (IOException e) {
        e.printStackTrace();
    }


    buttonOn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int temp = 2;
            bhari b = new bhari();
            b.execute(String.valueOf(temp));

        }
    });

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int temp = 1;
            String fan = String.valueOf(temp);
            bhari b = new bhari();
            b.execute(fan);

        }
      });
    }
  }

bhari类:

    class bhari extends AsyncTask<String,Void,Integer>{
     Socket socket;
   DataOutputStream dataOutputStream;

  @Override
  protected Integer doInBackground(String... params) {


          String massage = params[0];
    try {


        if(socket== null){

            System.out.println("if");
            socket = new Socket("192.168.0.79",8888);
            socket.getKeepAlive();
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.write(Integer.parseInt(massage));
            dataOutputStream.flush();
           // dataOutputStream.close();


        }else {
            System.out.println("Else");

            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.write(Integer.parseInt(massage));
            dataOutputStream.flush();
           // dataOutputStream.close();

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("End");
    return null;
    }
 }

2 个答案:

答案 0 :(得分:0)

实际上,您是在asynctask内创建另一个套接字对象。 如果要使用相同的套接字对象,则也必须将其传递给asynctask。 其另一种解决方案是将整数值传递给asynctask,但仅在asynctask内部创建套接字

答案 1 :(得分:0)

您只需要创建一个单例

class Mysocket{
private static Socket socket;

public static Socket getInstance()
{
if(socket==null)
{
   socket = new Socket("192.168.0.79",8888);
        socket.getKeepAlive();
}
return socket;
}


}