简体   繁体   中英

Server socket doesn't open port Android

I want to connect to my server building in Android, but I can't, I don't know how to connect it. I think my code is fine. I changed Manifest with Permission INTERNET.

package com.android.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    private static String TAG = "ServerSocketTest";
    EditText edittext1;
    private ServerSocket server;

    Runnable conn = new Runnable() {
        public void run() {

            try {
                edittext1.setText("Esperando0");
                server = new ServerSocket(9999);
                edittext1.setText("Esperando1");
                while (true) {
                    edittext1.setText("Esperando2");
                    Socket socket = server.accept();
                    if(socket.isConnected() == true){
                        edittext1.setText("socket is connected: " + socket.getRemoteSocketAddress().toString());
                    }
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String str = in.readLine();
                    Toast.makeText(getApplicationContext(), "BufferedReader ready", Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
                    Log.i("received response from server", str);
                    edittext1.setText("Conectado");
                    PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
                    salida.println("Conexion establecida");
                    in.close();
                    socket.close();
                }
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            } catch (Exception e) {             
                Log.e(TAG, e.getMessage());
            }
        }
    };

    @SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        edittext1 = (EditText)findViewById(R.id.editText1);
        Button boton1 = (Button)findViewById(R.id.button1);
        boton1.setOnClickListener(this);
        new Thread(conn).start();
    }

    @Override
    protected void onPause() {      
        super.onPause();
        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void onClick(View v) {

    }   
}

My client, it work very well.:

package com.clientesocketandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ClienteSocketAndroid extends Activity implements OnClickListener{
    String IP,mensaje, MensajeEntrada;
    int Port;
    Socket socket;
    ServerSocket SSocket;
    PrintWriter out;
    Button boton1, boton2,boton3;
    EditText edittext1,edittext2,edittext3,edittext4;
    TextView textview5;
    String mClientMsg = "";
    Thread myCommsThread = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cliente_socket_android);

        boton1 = (Button)findViewById(R.id.button1);
        boton1.setOnClickListener(this);
        boton2 = (Button)findViewById(R.id.button2);
        boton2.setOnClickListener(this);
        boton3 = (Button)findViewById(R.id.button3);
        boton3.setOnClickListener(this);
        edittext1 = (EditText)findViewById(R.id.editText1);
        edittext2 = (EditText)findViewById(R.id.editText2);
        edittext3 = (EditText)findViewById(R.id.editText3);
        edittext4 = (EditText)findViewById(R.id.editText4);

        Port = Integer.parseInt(edittext3.getText().toString());
        try {
            SSocket = new ServerSocket(Port);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            try {
                socket = SSocket.accept();
                Toast.makeText(getApplicationContext(), "Listo", Toast.LENGTH_SHORT).show();
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                MensajeEntrada = in.readLine();
                edittext4.setText(MensajeEntrada);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    @SuppressLint({ "NewApi", "NewApi", "NewApi" })
    public void onClick(View arg0) {
        if(arg0.getId() == R.id.button1){
             try {
                 IP = edittext2.getText().toString();
                 Port = Integer.parseInt(edittext3.getText().toString());
                 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                 StrictMode.setThreadPolicy(policy);
                 socket = new Socket(IP, Port);    //Abre un socket con el número de IP y de puerto.
                 if(socket.isConnected() == true){
                     Toast.makeText(getApplicationContext(), "Conectado", Toast.LENGTH_SHORT).show();
                 }
             } catch (UnknownHostException e) {
                 e.printStackTrace();
                 edittext1.setText(e.getMessage() + ": " + e.getCause());
             } catch (IOException e) {
                 e.printStackTrace();
                 edittext1.setText(e.getMessage() + ": " + e.getCause());
             }  
            }
        if(arg0.getId() == R.id.button3){
            try {
                mensaje = edittext1.getText().toString();
                PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
                salida.println(mensaje); 
                edittext1.setText("");
                //hace falta concatenacion
                edittext4.setText("" + "\n" + mensaje + "");
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Mensaje NO enviado", Toast.LENGTH_SHORT).show();
            }     
        }
        if(arg0.getId() == R.id.button2){
            try {
                PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
                salida.println("bye"); 
                Toast.makeText(getApplicationContext(), "Conexión cerrada", Toast.LENGTH_SHORT).show();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Error al cerrar sesion", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

I thank your Help!!

The algorithm shows that whenever your socket is connected or not, you always create a buffered i/O stream and sending the data

The following is my suggested pseudo code for server

try(socket successfully connected) {
    try( server is synchronized with the client)  socket.accept();
 // create the Object I/O  stream

 } show error

for Client

//Create a new socket with IP address and port number
try 
client connect to server with aforementioned parameters with timeout

  create a Object I/O stream
   catch (IOException)

One problem that I see with your code is, you cannot update Ui elements from Non Ui thread, that is why it is raising exception, but you have caught all the exceptions.

So remove all setText calls from the runnable.

edittext1.setText("Conectado");

Use runonUithread or any other methods to update UI elements, and do not catch all exceptions like you have done. It is quite difficult to debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM