Client-server connection via socket

Asked

Viewed 3,232 times

0

I need to make a connection via socket as follows:

My Android app has a "Confirm" button - when you click 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 "data successfully registered!".

But he’s 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();

                }
            });


    }
}

Servidorsocket.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();


      }
   }
}
  • Networkingonmainthreadexception, it is giving this error???? Because connections like this are not allowed, not even in Runnable in the UI thread. You’d have to create an asynctask to make this kind of call.

2 answers

0


You have to make every internet call outside the UI thread, even if it’s within a Runnable like you did, the thread still remains in the UI. I will place two blocks of code to illustrate a solution:

Commasynctask.java, where I create the task in background:

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: https://github.com/codepath/android_guides/wiki/Sending-and-Receiving-Data-with-Sockets

  • 1

    Can you give an example of how to do that? External links are good for bringing references and other information - but the solution should be available here, in full (links may change or simply cease to exist).

  • I edited the answer with a code snippet

  • I appreciate the help, clarified some doubts I was having. Thank you!

-1

I establish the connection different than 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
}
  • 3

    You can explain better why her code doesn’t work, and why her change will fix the problem?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.