C
C
CeBePHblY2016-02-05 19:47:31
Android
CeBePHblY, 2016-02-05 19:47:31

(Still unresolved) Socket client. How to constantly monitor whether there is data from the server?

There is a client:

import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;

public class LoginActivity extends AppCompatActivity {

    Button buttonEnter;
    TextView textViewHeader;
    EditText editTextLogin;
    Handler handler;
    Socket client = null;
    DataOutputStream dataToServerStream = null;
    DataInputStream dataFromServerStream = null;

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


        buttonEnter = (Button) findViewById(R.id.buttonEnter);
        textViewHeader = (TextView) findViewById(R.id.textViewHeader);
        editTextLogin = (EditText) findViewById(R.id.editTextLogin);

        //вынос подключения к серверу в отдельный поток
        class ConnectToServer extends AsyncTask<Void, Void, Void>{

            @Override
            protected Void doInBackground(Void... voids) {
                //подключение к серверу
                try {
                    client = new Socket("193.106.169.249", 1605);
                    //чтение данных с сервера
                    /*dataFromServerStream = new DataInputStream(client.getInputStream());
                    String r="";
                    byte[] readBuffer=new byte[5*1024];
                    int read=dataFromServerStream.read(readBuffer);
                    if(read!=-1)
                    {
                        byte[] readData=new byte[read];
                        System.arraycopy(readBuffer,0,readData,0,read);
                        try{
                            r = new String(readData, "UTF-8");
                        }catch(UnsupportedEncodingException e){}
                    }*/
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    System.out.println("Got an IOException: " + e.getMessage());
                }
                return null;
            }
        }


        
        //запуск подключения к серверу
        final ConnectToServer setConnectToServer = new ConnectToServer();
        setConnectToServer.execute();

        //обработчик нажатий
        View.OnClickListener OnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.buttonEnter:

                        //отправка данных на сервер
                        try {
                            String str;
                            dataToServerStream = new DataOutputStream(client.getOutputStream());
                            str = editTextLogin.getText().toString();
                            byte[] buf = str.getBytes("UTF-8");
                            dataToServerStream.write(buf, 0, buf.length);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        };

        buttonEnter.setOnClickListener(OnClickListener);
    }
}

Создал AsyncTask с подключением к серверу, при нажатии на кнопку логин отправляется серверу. Как теперь сделать, чтобы клиент постоянно мониторил, есть ли данные с сервера? Допустим после отправки логина/пароля сервер проверяет их и если все верно он отправляет клиенту команду "OK", а если нет, то отправляет "ERROR", клиент видит что есть данные, и в зависимости от пришедших данных открывает новое активити, либо выводит сообщение о том, что логин/пароль не верны. Если я правильно понимаю, то нужно код
dataFromServerStream = new DataInputStream(client.getInputStream());
                    String r="";
                    byte[] readBuffer=new byte[5*1024];
                    int read=dataFromServerStream.read(readBuffer);
                    if(read!=-1)
                    {
                        byte[] readData=new byte[read];
                        System.arraycopy(readBuffer,0,readData,0,read);
                        try{
                            r = new String(readData, "UTF-8");
                        }catch(UnsupportedEncodingException e){}
                    }

run in a new AsyncTask, and wrap it in while and try? It is necessary that on each activity, with a certain action (for example, pressing a button), a command is sent to the server and a constant reading of data from the server. Let's say the user clicked the "Friends" tab, the "SHOW_FRIENDS" command was sent to the server, and the server generated the data and sent it to the client, the client sees that the data is there and parses it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
razer89, 2016-02-05
@razer89

A socket is a very unreliable thing, especially when using mobile internet. Try looking into GCM , which guarantees message delivery and has a nice Android client API.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question