Client-server connection via socket

0

I need to make a socket connection as follows:

My Android application has a "Confirm" button - when clicking the button it has to send a message to the server and after that the server has to return a message to my application stating "successfully registered data!".

But he is not connecting to the server. What's wrong?

  

Android Manifest XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.isadoraoliveira.testeapp">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  

MainActivity.java

package com.isadoraoliveira.testeapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private static final String hostname = "localhost";
    private static final int portaServidor = 6789;
    Socket socket = null;
    private Button button;

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

            button = (Button) findViewById(R.id.button);

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

            new Thread(new Runnable()){

            @Override
                public void run (){

            try {
            socket = new Socket(hostname, portaServidor);

            //dados enviados para o servidor
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        bw.write("Dados enviados para o servidor");
                        bw.newLine();
                        bw.flush();

            //dados reebidos pelo servidor
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        System.out.println("Dados cadastrados " + br.readLine()); //retornar ok

            socket.close();
                    }
                    catch(IOException e) {
                        e.printStackTrace();
                    }

            }

            });.start();

                }
            });


    }
}
  

ServerSocket.java

import java.io.*;
import java.net.*;

class ServidorSocket
{
   private static int portaServidor = 6789;

   public static void main(String argv[]) throws Exception{

      ServerSocket ServerSocket = null;
      ServerSocket = new ServerSocket(portaServidor);

      while(true){

            System.out.println("Servidor iniciado!");
            Socket socket = ServerSocket.accept();

            //recebe mensagem do cliente - mensagem vai ser passada por meio do botão android
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("Mensagem do cliente " + br.readLine()); // ok

            //envia mensagem para o cliente - talvez não precise
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("Dados cadastrados com sucesso!");
            bw.newLine();
            bw.flush();


      }
   }
}
    
asked by anonymous 21.06.2017 / 20:45

2 answers

0

You have to make every internet call out of the UI thread, even though it's inside a Runnable as it did, the thread still remains UI. I'll put two blocks of code to illustrate a solution:

CommAsyncTask.java, where I create the background task:

package com.grupoestudos.myapplication;

import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Arrays;

public class CommAsyncTask extends AsyncTask<String, Integer, String> {
    private static final String hostname = "localhost";
    private static final int portaServidor = 6789;
    private IAsyncHandler mHandler;

    public CommAsyncTask(IAsyncHandler mHandler) {
        this.mHandler = mHandler;
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            Socket socket = new Socket(hostname, portaServidor);

            //dados enviados para o servidor
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            //Estou usando Arrays.toString(), somente para ele pegar todas as strings que passar no
            //método.
            bw.write(Arrays.toString(params));
            bw.newLine();
            bw.flush();

            //dados reebidos pelo servidor
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String retorno =  "Dados cadastrados " + br.readLine(); //retornar ok
            socket.close();

            return retorno;
        }
        catch(IOException e) {
            return e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        //Aqui você utiliza o retorno do doInBackground
        //Aqui é interessante usar um EventBus, ou alguma outra classe para poder enviar essa
        //informação para a interface.
        mHandler.postResult(result);
    }
}

And MainActivity.java, where you will make the call and take advantage of the result:

package com.grupoestudos.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements IAsyncHandler{

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

        //Cria a tarefa para ser executada em background
        CommAsyncTask task = new CommAsyncTask(MainActivity.this);

        //Aqui eu chamo a execução. Como é em background, por isso citei de usar um EventBus ou outra
        //forma de poder recuperar a informação. Não é a melhor forma, mas de forma ilustrativa, vou
        //criar um método para receber a informação e aproveitar na activity.
        task.execute("Dados enviados para o servidor");
    }

    @Override
    public void postResult(String result) {
        //Neste método você pega o resultado da asynctask e aproveita de alguma forma
    }
}

interface IAsyncHandler {
    void postResult(String result);
}

Take a look at this guide that it helps: link

    
21.06.2017 / 20:54
0

I make the connection different from what you did:

// imports:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

// code:

SocketAddress sockaddr = new InetSocketAddress(host, port);
socket = new Socket();
socket.connect(sockaddr, timeout);

if(socket.isConnected()){
//se estiver conectado eu deu um write e o read
}
    
21.06.2017 / 20:59