There is an activit that launches AsyncTask:

public class MainActivity extends ActionBarActivity implements View.OnClickListener { SocketAsync SocketAsync = new SocketAsync(); ConfigSocket config = new ConfigSocket(); Button btnEnter; Button btnFight; //выводит все элементы этого активити @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //убираю ActionBar getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //убираю заголовок приложения ActionBar actionBar = getSupportActionBar(); actionBar.hide(); setContentView(R.layout.activity_main); //подключаем лауер-файл с элементами //находим эти элементы по ID btnEnter = (Button) findViewById(R.id.btnEnter); btnFight = (Button) findViewById(R.id.btnFight); // присваиваем обработчик кнопкам btnEnter.setOnClickListener(this); btnFight.setOnClickListener(this); SocketAsync.execute(); } //обработчик нажатий на кнопки @Override public void onClick(View v) { // по id определеяем кнопку, вызвавшую этот обработчик switch (v.getId()) { case R.id.btnEnter: config.setSOCKET_MESSAGE("12345"); break; case R.id.btnFight: config.setSOCKET_MESSAGE("12345"); break; } } 

AsyncTask code:

  public class SocketAsync extends AsyncTask <Void, Integer, Void> { public Socket socket; public String message; ConfigSocket config = new ConfigSocket(); @Override protected Void doInBackground(Void... params) { //конект с сервером try { if (config.getSOCKET_CONNECTED() == false) { InetAddress serverAddr = InetAddress.getByName(config.SERVER_ADDR); socket = new Socket(serverAddr, config.SERVER_PORT); config.setSOCKET_CONNECTED(true); } } catch (Exception e) { e.printStackTrace(); } //создает новый поток для отправки сообщений Thread threadWrite = new Thread(new Runnable() { @Override public void run() { send(socket); } }); threadWrite.start(); // запускаем на отправку //пока есть конект с сервером, цикл ждет приема сообщений while (socket != null && socket.isConnected()) { //Message m = new Message(); //m.what = 2; try { //переменная для получение данных BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream())); String st = null; st = input.readLine(); } catch (IOException e) { e.printStackTrace(); } } threadWrite.stop(); return null; } protected void send(Socket socket) { PrintWriter out = null; //пока есть конект с сервером, цикл ждет сообщение на отправку while (socket != null && socket.isConnected()) { if (config.getSOCKET_MESSAGE() = null) { //Log.d("Send Message", config.SOCKET_MESSAGE); try { out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(config.getSOCKET_MESSAGE()); } catch (Exception e) { return; } config.setSOCKET_MESSAGE(null); } } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); //если связь разорвалась.... if (socket == null || !socket.isConnected()) { config.setSOCKET_CONNECTED(false); } } 

and there is such a class:

 public class ConfigSocket { boolean SOCKET_CONNECTED = false; String SERVER_ADDR = "192.168.1.23"; int SERVER_PORT = 8888; String SOCKET_MESSAGE = null; public String getSOCKET_MESSAGE() { //геттер SOCKET_MESSAGE return this.SOCKET_MESSAGE; } public void setSOCKET_MESSAGE(String SOCKET_MESSAGE) { //сеттер SOCKET_MESSAGE this.SOCKET_MESSAGE = SOCKET_MESSAGE; } public boolean getSOCKET_CONNECTED() { //геттер SOCKET_CONNECTED return this.SOCKET_CONNECTED; } public void setSOCKET_CONNECTED(boolean SOCKET_CONNECTED) { //сеттер SOCKET_CONNECTED this.SOCKET_CONNECTED = SOCKET_CONNECTED; } } 

Help me to understand. This is how I think. AsyncTask launches a new stream, where it connects to the server (which the server informs me that the new client has successfully connected) and until the connection is broken through the loop, it must wait for incoming information. And another stream is started, which should send a message to the server. Its loop should scan the SOCKET_MESSAGE variable from the ConfigSocket class, if it is not null , then send a message to the server. By activating the button, I set the variable value, but the message is not sent. And if before launching the application in ConfigSocket prescribe the value SOCKET_MESSAGE , then it will be sent.

Please tell me what I'm doing wrong and how to implement it all correctly? Because I'm already the third day trying to figure it out. Thank you very much in advance.

    1 answer 1

    You use two different instances of ConfigSocket in SocketAsync and MainActivity , you need to pass an instance of ConfigSocket in the constructor or in the execute parameters

    It should also be noted that your access to SOCKET_MESSAGE is not synchronized in any way and the use of Thread.stop not recommended, and in your case it is also meaningless (if it reaches this line, the socket will be closed and the second stream will come out without coercion)

    • I read about it yesterday, but there are common examples. If it's not difficult for you, please show it in the code on my example with comments, so that I would always and always understand how to do it. Thank you very much in advance. - Vitaliy Fesyura
    • I'm afraid it is better for you to ask specific questions - correct the error with two instances of ConfigSocket and try to access shared variables only through syncronized blocks, if something goes wrong - create another question - Alexander Kudrevatykh
    • Thanks a lot, I figured out how to synchronize and transfer one instance of the class to other threads. - Vitaliy Fesyura
    • one last question. I have a condition (socket! = Null && socket.isConnected ()), but when I close the server program or my wife turns off the router, it still thinks that socket.isConnected () = true. Tell me how to check this connection gap correctly. - Vitaliy Fesyura
    • Judging by the documentation, isConnected means that we managed to contact the server, what happens to the socket after that - it doesn't matter anymore, true will always return. Most likely you need to use the isClosed method - Alexander Kudrevatykh