C
C
CeBePHblY2016-02-03 14:37:55
Android
CeBePHblY, 2016-02-03 14:37:55

Android work with sockets. How to get data from the server?

I'm learning Android. There is a server in Python, it waits for clients to connect (clients are also in Python), after connecting, clients send server commands, and it sends a response in response (everything works fine). Now the task is to replace Python clients with Android clients. The connection to the server takes place, it receives the "get" command from the client, the server immediately sends a response. How can I get this data in Android? And one more thing: as I understand it, is it better to send commands and receive data in a separate thread?

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

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.net.UnknownHostException;

public class LoginActivity extends AppCompatActivity {

    Button buttonEnter;
    TextView textviewHeader;
    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);

        //хандлер класс
        class MyHandler extends Handler {

            WeakReference<LoginActivity> wrActivity;

            public MyHandler(LoginActivity activity) {
                wrActivity = new WeakReference<>(activity);
            }

            @Override
            public void handleMessage(android.os.Message msg){
                super.handleMessage(msg);
                LoginActivity activity = wrActivity.get();
                if (activity != null)
                    switch (msg.what){
                        case 0:
                            activity.textviewHeader.setText("Подключение к серверу...");
                            break;
                        case 1:
                            Toast toast = Toast.makeText(getApplicationContext(),msg.obj.toString(), Toast.LENGTH_LONG);
                            toast.show();
                        case 2:
                            activity.textviewHeader.setText("Войдите в приложение");
                            activity.buttonEnter.setEnabled(true);
                            break;
                    }
            }
        }
        handler = new MyHandler(this);

        //новый поток
        Thread threadConnect = new Thread(new Runnable() {
            Message msg;

            @Override
            public void run() {
                handler.sendEmptyMessage(0);
                //подключение к серверу
                try {
                    client = new Socket("localhost", 1605);
                    client.setSoTimeout(100);
                    dataToServerStream = new DataOutputStream(client.getOutputStream());
                    dataFromServerStream = new DataInputStream(client.getInputStream());

                    //отправка данных на сервер
                    dataToServerStream.writeUTF("get");
                    //чтение данных с сервера

                    msg = handler.obtainMessage(1,0,0, dataFromServerStream.readUTF());
                    handler.sendMessage(msg);

                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    System.out.println("Got an IOException: " + e.getMessage());
                }
                handler.sendEmptyMessage(2);
            }
        });
        threadConnect.start();

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

        buttonEnter.setOnClickListener(OnClickListener);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Perelygin, 2016-02-03
@orcDamnar

well, if you want to work with sockets, then just like everywhere else: parse bytes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question