Sei sulla pagina 1di 10

Hola a tod@s! Estoy intentando llevar a cabo lo sigiuente...

Quiero un programa que me cree un servidor en un dispositivo android y otro que me cree un cliente en otro dispositivo android distinto. El objetivo es que ambos dispositivos se puedan comunicar va TCP al conectarse a la misma red WiFi. Creo que estoy bastante cerca de la solucin pero no me funciona cuando intento probarlo con los dos dispositivos . Cualquier ayuda ser muy agradecida. Un saludo ANDROID SERVER
Cdigo : public class TcpServer extends Activity { /** Called when the activity is first created. */ private TextView textDisplay; private EditText editText; private Button btn_send; private Socket s; private ServerSocket ss = null; private boolean sending = false; public String outgoingMsg; public String info = null; private static final int TCP_SERVER_PORT = 8888; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); textDisplay = (TextView) this.findViewById(R.id.textView1); btn_send = (Button) this.findViewById(R.id.button1); editText = (EditText) this.findViewById(R.id.editText1); textDisplay.setText(""); btn_send.setOnClickListener(new OnClickListener() { public void onClick(View v) { outgoingMsg = editText.getText().toString()+ System.getProperty("line.separator");; sending = true; } }); sendOperation(); receiveOperation(); } final Handler mHandler = new Handler(); // Create runnable for posting final Runnable mUpdateResults = new Runnable() { public void run() { updateResultsInUI(); } }; private void updateResultsInUI(){

textDisplay.append(info); } protected void receiveOperation(){ Thread rThread = new Thread(){ //@Override public void run() { // TODO Auto-generated method stub try { Log.d("TCP", "S: Conectando..."); ss = new ServerSocket(TCP_SERVER_PORT); s = ss.accept(); Log.d("TCP", "S: Conectado"); while (true) { try { Log.d("TCP", "S: Recibiendo..."); BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); String incomingMsg = in.readLine() + System.getProperty("line.separator"); Log.i("TcpServer", "received: " + incomingMsg); Log.d("TCP", "S: Recibido: '" + incomingMsg + "'"); Log.d("TCP", "S: Enviando..."); info = "Recieved: " + incomingMsg; } catch(Exception e) { Log.e("TCP", "S: Error", e); } finally { s.setKeepAlive(true); Log.d("TCP", "S: Done."); } mHandler.post(mUpdateResults); } } catch (Exception e) { Log.e("TCP", "S: Error", e); } } }; rThread.start(); } protected void sendOperation(){ Thread sThread = new Thread(){ //@Override public void run() { // TODO Auto-generated method stub ServerSocket ss = null; try { if (!s.isConnected()){ s = ss.accept(); } while (true) { if (sending){ try { Log.d("TCP", "S: Recibiendo..."); BufferedWriter out

= new BufferedWriter (new OutputStreamWriter(s.getOutputStream())); if (outgoingMsg != null){ out.write(outgoingMsg); Log.d("TCP", "S: Enviado: '" + outgoingMsg + "'"); out.flush(); Log.i("TcpServer", "sent: " + outgoingMsg); info = "Sent: " + outgoingMsg; outgoingMsg = null; } sending = false; } catch(Exception e) { Log.e("TCP", "S: Error", e); } finally { s.setKeepAlive(true); Log.d("TCP", "S: Done."); } mHandler.post(mUpdateResults); } } } catch (Exception e) { Log.e("TCP", "S: Error", e); } } }; sThread.start(); } }

ANDROID CLIENT
Cdigo : public class TcpClient extends Activity { /** Called when the activity is first created. */ private TextView textView1; private Button button, btnConnect; private EditText editText; private String outMsg; private String info; private boolean connected = false; private Boolean sending = false; private static final int TCP_SERVER_PORT = 8888; private Socket s; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); textView1 = (TextView) this.findViewById(R.id.textView1); button = (Button) this.findViewById(R.id.button1); btnConnect = (Button) this.findViewById(R.id.button2); editText = (EditText) this.findViewById(R.id.editText1);

button.setOnClickListener(new OnClickListener() { public void onClick(View v) { outMsg = editText.getText().toString() + System.getProperty("line.separator"); sending = true; } }); receiveOperation(); sendOperation(); } final Handler mHandler = new Handler(); // Create runnable for posting final Runnable mUpdateResults = new Runnable() { public void run() { updateResultsInUI(); } }; private void updateResultsInUI(){ textView1.append(info); } protected void receiveOperation(){ Thread rThread = new Thread(){ public void run() { // TODO Auto-generated method stub try { Log.d("TCP", "C: Conectando..."); Socket s = new Socket("192.168.1.115", TCP_SERVER_PORT); Log.d("TCP", "C: Conectado"); while(true){ try { BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); Log.d("TCP", "C: Receiving..."); String inMsg = in.readLine() + System.getProperty("line.separator"); Log.i("TcpClient", "received: " + inMsg); info = inMsg; } catch(Exception e) { Log.e("TCP", "S: Error intern", e); } finally { s.setKeepAlive(true); } mHandler.post(mUpdateResults); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } };

rThread.start(); } protected void sendOperation(){ Thread sThread = new Thread(){ public void run() { // TODO Auto-generated method stub try { s = new Socket("192.168.1.115", TCP_SERVER_PORT); while (true) { if (sending){ try { Log.d("TCP", "C: Connected"); PrintWriter out = new PrintWriter (new OutputStreamWriter(s.getOutputStream())); if (outMsg != null) { Log.d("TCP", "C: Sending..."); out.write(outMsg); } out.flush(); Log.d("TCP", "C: Enviado."); Log.i("TcpClient", "sent: " + outMsg); sending = false; } catch(Exception e) { Log.e("TCP", "S: Error", e); } finally { s.setKeepAlive(true); } } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; sThread.start(); } }

Diablins

Publicado: Vie Jun 08, 2012 11:23 am del mensaje:

Ttulo

Mensajes: 46

te aconsejo que expliques "por qu no funciona" y que es lo que ocurre cuando ejecutas, explota, no hace nada, muestra esto pero lo otro no... ayudas a no perder el tiempo en leer todo el cdigo

Helenalg89

Publicado: Vie Jun 08, 2012 1:01 pm mensaje:

Ttulo del

Diablins escribi:
Mensajes: 10

te aconsejo que expliques "por qu no funciona" y que es lo que ocurre cuando ejecutas, explota, no hace nada, muestra esto pero lo otro no... ayudas a no perder el tiempo en leer todo el cdigo

Simplemente no consigo conectar un dispositivo con el otro, por consiguiente ni consigo enviar ni recibir nada desde ninguno de los dos lados... Sin embargo, tengo un programa en visual basic que me simula un servidor y un cliente y con esos s que funciona... No se qu puede ser... Me estoy quedando sin ideas... El cdigo lo que hace es abrir el socket correspondiente en cada caso y luego conectarlo al puerto que voy a usar para pasar la informacin (en este caso el 8888), y en el caso del cliente le expecificamos la direccin IP del servidor. Tras eso habro en cada lado los buffers de entrada y salida y envo datos y recivo. Esto lo he hecho en dos funciones separadas para poder enviar o recibir en el orden que yo prefiera. Espero que te sirva como resumen...
Ultima edicin por Helenalg89 el Vie Jun 08, 2012 1:12 pm; editado 1 vez

Helenalg89

Publicado: Vie Jun 08, 2012 1:08 pm mensaje:

Ttulo del

Mensajes: 10

Hay alguna forma de que un programa que haga de servidor sepa si el cliente tiene establecida la conexin con l o vicebersa? Es decir... Si estoy en el lado del cliente quiero saber si el servidor est operativo, y si estoy en el lado del servidor si lo est el cliente. Porque utilizando Server.isConnected() en el momento en el que se conecta se quda as, y aunque por el otro lado lo desactive no pasa nada...
Publicado: Mar Jun 12, 2012 12:39 pm Ttulo del mensaje: Re: Comunicacin via TCP Servidor y Cliente en dos programas

Helenalg89

Mensajes: 10

Hola a todos!! Finalmente lo consegu resolver, dejo el cdigo, os dejo aqu las nuevas funciones en las que he implementados los threads:

LA PARTE DEL SERVIDOR


Cdigo : protected void connectOp(){ Thread connectTh = new Thread(){ public void run(){ while (true){ if (btnConnect.getText() == "Disconnect" && !connection){ try { mHandler.post(mUpdateResults); ss = new ServerSocket(PORT); Log.i("TCP","Server bounded to port " + PORT); s = ss.accept(); Log.i("TCP","Client connected to the Server"); connection = true; clientCon = true; //Set TimeOut s.setSoTimeout(500); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); connection = false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); connection = false; } } while(connection && btnConnect.getText() == "Disconnect" && clientCon){ try { connection = !s.isClosed(); if (connection){Log.i("TCP", "Connection: true");} else{Log.i("TCP", "Connection: false");} //Buffers initialization BufferedReader input = new BufferedReader(newInputStreamReader(s.getInputStream()) ); PrintWriter output = new PrintWriter(newOutputStreamWriter(s.getOutputStream())) ; //Send function if (outMsg != null){ output.write(outMsg + " recived"); Log.d("TCP", "Sent Data: " + outMsg); outMsg = null; output.flush(); }

//Receive function inMsg = input.readLine(); if (inMsg == null){clientCon = false;} Log.d("TCP", "Received Data: " + inMsg); mHandler.post(mUpdateResults); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Close Socket if((btnConnect.getText() == "Connect" && connection)||(!clientCon && connection)){ try { ss.close(); s.close(); Log.d("TCP", "Server and Client Socket closed"); //connection = false; connection = !ss.isClosed(); if (connection){Log.i("TCP", "Connection: true");} else{Log.i("TCP", "Connection: false");} } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }; connectTh.start(); }

LA PARTE DEL CLIENTE


Cdigo : protected void connectOp(){ Thread connectTh = new Thread(){ public void run(){ while (true){ if (btnConnect.getText() == "Disconnect" && !connection){ try {

Log.i("TCP", "Connecting..."); s = new Socket("192.168.1.115", PORT); serverCon = true; Log.d("TCP", "Connected"); connection = true; //Set TimeOut s.setSoTimeout(500); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); connection = false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); connection = false; } } while(connection && btnConnect.getText() == "Disconnect" && serverCon){ try { //Buffers initialization input = new BufferedReader(new InputStreamReader(s.getInputStream() )); output = new PrintWriter(new OutputStreamWriter(s.getOutputStream()) ); //Send function if (sentMsg != null){ output.write(sentMsg); Log.d("TCP", "Sent Data: " + sentMsg); sentMsg = null; output.flush(); } //Receive function recMsg = input.readLine(); Log.d("TCP", "Received Data: " + recMsg); if (recMsg == null){serverCon = false;} mHandler.post(mUpdateResults); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection && btnConnect.getText() == "Connect" || !serverCon && connection) //Close Socket

try { s.close(); connection = false; Log.d("TCP", "Client Closed"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; connectTh.start(); }

Potrebbero piacerti anche