0

我想连接到我在 Android 中构建的服务器,但我不能,我不知道如何连接它。我认为我的代码很好。我使用许可 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) {

    }   
}

我的客户,它工作得很好。:

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

我感谢您的帮助!!

4

2 回答 2

0

该算法表明,无论您的套接字是否连接,您总是会创建一个缓冲的 i/O 流并发送数据

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

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

 } show error

为客户

//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)
于 2012-10-22T04:15:03.150 回答
0

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

所以从 runnable 中删除所有 setText 调用。

edittext1.setText("Conectado");

使用 runonUithread 或任何其他方法来更新 UI 元素,不要像以前那样捕获所有异常。调试起来相当困难。

于 2012-10-22T04:17:36.677 回答