服务器套接字无法打开Android端口

时间:2012-10-22 03:35:11

标签: android sockets port serversocket

我想连接到Android中的服务器构建,但我不能,我不知道如何连接它。我认为我的代码很好。我用Permission INTERNET更改了Manifest。

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) {

    }   
}

我的客户,它运作良好。:

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();
            }
        }
    }
}

我感谢你的帮助!!

2 个答案:

答案 0 :(得分:0)

算法显示无论何时连接套接字,您始终都会创建缓冲的I / O流并发送数据

以下是我建议的服务器伪代码

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)

答案 1 :(得分:0)

我在您的代码中看到的一个问题是,您无法从Non Ui线程更新Ui元素,这就是它引发异常的原因,但是您已经捕获了所有异常。

因此,从runnable中删除所有setText调用。

edittext1.setText("Conectado");

使用runonUithread或任何其他方法更新UI元素,并且不会捕获所有异常。调试非常困难。