Connexion par socket entre smartphone Android et application Java sur PC
Répondre à la discussion
Affichage des résultats 1 à 10 sur 10

Connexion par socket entre smartphone Android et application Java sur PC



  1. #1
    chahbane

    Connexion par socket entre smartphone Android et application Java sur PC


    ------

    Bonsoir,
    J'ai un vrai problème. depuis 2 jours je cherches, j'ai trouvé plein de solutions mais aucune d'entre elles ne fonctionne.
    je souhaite programmer une application sur Android et une application Java sur mon PC et pouvoir communiquer entre eux via les sockets mais rien ne se passe dans l'application Java (serveur) et l'application Cliient sur android se plante.
    j'ai ajouté les permissions d'utilisation d internet.

    ciode coté serveur (application sur PC)
    Code:
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    
    public class TCPServer {
        public static void main(String args[]) {
    // declaration section:
    // declare a server socket and a client socket for the server
    // declare an input and an output stream
            ServerSocket echoServer = null;
            String line;
            DataInputStream is;
            PrintStream os;
            Socket clientSocket = null;
    // Try to open a server socket on port 11000
    // Note that we can't choose a port less than 1023 if we are not
    // privileged users (root)
            try {
               echoServer = new ServerSocket(11000);
            }
            catch (IOException e) {
               System.out.println(e);
            }   
    // Create a socket object from the ServerSocket to listen and accept 
    // connections.
    // Open input and output streams
        try {
               clientSocket = echoServer.accept();
               is = new DataInputStream(clientSocket.getInputStream());
               os = new PrintStream(clientSocket.getOutputStream());
    // As long as we receive data, echo that data back to the client.
               while (true) {
                 line = is.readLine();
                 os.println(line); 
               }
            }   
        catch (IOException e) {
               System.out.println(e);
            }
        }
    }

    Le code cotée Client (android)

    Code:
    package com.sdz.tcpclient;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    import android.support.v7.app.ActionBarActivity;
    import android.support.v7.app.ActionBar;
    import android.support.v4.app.Fragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.os.Build;
    
    public class MainActivity extends ActionBarActivity implements OnClickListener{
    	Button b;
    	EditText et;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		b = (Button) findViewById(R.id.button1);
    		b.setOnClickListener(this);
    		et = (EditText) findViewById (R.id.editText1);
    		et.setText("test1");
    	}
    
    	public void client()
    	{
    
    		// declaration section:
    		// s: our client socket
    		// os: output stream
    		// is: input stream
    		        Socket s = null;  
    		        DataOutputStream os = null;
    		        DataInputStream is = null;
    		// Initialization section:
    		// Try to open a socket on port 25
    		// Try to open input and output streams
    		        try {
    		            s = new Socket("192.168.1.64", 11000);
    		            os = new DataOutputStream(s.getOutputStream());
    		            is = new DataInputStream(s.getInputStream());
    		            et.setText("connected");
    		        } catch (UnknownHostException e) {
    		            System.err.println("Don't know about host: hostname");
    		        } catch (IOException e) {
    		            System.err.println("Couldn't get I/O for the connection to: hostname");
    		        }
    		// If everything has been initialized then we want to write some data
    		// to the socket we have opened a connection to on port 25
    		    if (s != null && os != null && is != null) {
    		            try {
    		// The capital string before each colon has a special meaning to SMTP
    		// you may want to read the SMTP specification, RFC1822/3
    		        os.writeBytes("HELO\n");    
    		        os.writeBytes("QUIT");
    		        et.setText("sent");
    		// keep on reading from/to the socket till we receive the "Ok" from SMTP,
    		// once we received that then we want to break.
    		                String responseLine;
    		                while ((responseLine = is.readLine()) != null) {
    		                    System.out.println("Server: " + responseLine);
    		                    if (responseLine.indexOf("IT") != -1) {
    		                      break;
    		                    }
    		                }
    		// clean up:
    		// close the output stream
    		// close the input stream
    		// close the socket
    		        os.close();
    		                is.close();
    		                s.close();
    		                et.setText("finish");
    		            } catch (UnknownHostException e) {
    		                System.err.println("Trying to connect to unknown host: " + e);
    		            } catch (IOException e) {
    		                System.err.println("IOException:  " + e);
    		            }
    		        }
    	}
    
    	@Override
    	public void onClick(View v) {
    		// TODO Auto-generated method stub
    		client();
    	}
    	
    }
    merci pour votre reponses

    -----

  2. #2
    Arzhur

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    Bonjour,


    Comme ça je ne vois pas d'erreur (d'ailleurs ça marche très bien entre 2 pc).


    Quand tu dis que l'application plante côté client : c'est à dire ? Tu as une exception avec la trace ?

  3. #3
    chahbane

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    Un message d'erreur apparait sur le smartphone : "l'application s'est arretee"

  4. #4
    chahbane

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    le fichier log :
    05-03 14:18:09.082: E/Trace(2202): error opening trace file: No such file or directory (2)
    05-03 14:18:10.331: I/Choreographer(2202): Skipped 85 frames! The application may be doing too much work on its main thread.
    05-03 14:18:10.482: D/gralloc_goldfish(2202): Emulator without GPU emulation detected.
    05-03 14:18:12.292: D/AndroidRuntime(2202): Shutting down VM
    05-03 14:18:12.301: W/dalvikvm(2202): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
    05-03 14:18:12.351: E/AndroidRuntime(2202): FATAL EXCEPTION: main
    05-03 14:18:12.351: E/AndroidRuntime(2202): android.os.NetworkOnMainThread Exception
    05-03 14:18:12.351: E/AndroidRuntime(2202): at android.os.StrictMode$AndroidB lockGuardPolicy.onNetwork(Stri ctMode.java:1117)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at libcore.io.BlockGuardOs.connec t(BlockGuardOs.java:84)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at libcore.io.IoBridge.connectErr no(IoBridge.java:127)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at libcore.io.IoBridge.connect(Io Bridge.java:112)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.net.PlainSocketImpl.conne ct(PlainSocketImpl.java:192)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.net.PlainSocketImpl.conne ct(PlainSocketImpl.java:172)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.net.Socket.startupSocket( Socket.java:566)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.net.Socket.tryAllAddresse s(Socket.java:127)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.net.Socket.<init>(Socket. java:177)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.net.Socket.<init>(Socket. java:149)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at com.sdz.tcpclient.MainActivity .client(MainActivity.java:50)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at com.sdz.tcpclient.MainActivity .onClick(MainActivity.java:96)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at android.view.View.performClick (View.java:4204)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at android.view.View$PerformClick .run(View.java:17355)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at android.os.Handler.handleCallb ack(Handler.java:725)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at android.os.Handler.dispatchMes sage(Handler.java:92)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at android.os.Looper.loop(Looper. java:137)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at android.app.ActivityThread.mai n(ActivityThread.java:5041)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.lang.reflect.Method.invok eNative(Native Method)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at java.lang.reflect.Method.invok e(Method.java:511)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at com.android.internal.os.Zygote Init$MethodAndArgsCaller.run(Z ygoteInit.java:793)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at com.android.internal.os.Zygote Init.main(ZygoteInit.java:560)
    05-03 14:18:12.351: E/AndroidRuntime(2202): at dalvik.system.NativeStart.main (Native Method)

  5. A voir en vidéo sur Futura
  6. #5
    Arzhur

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    Je ne connais pas l'API Android. Mais sur le net je trouve ce genre de truc : https://stackoverflow.com/questions/...droid-emulator

    Apparemment il ne faut pas ouvrir une connexion depuis le Thread principale : Essaye de lancer ta méthode client dans un Thread à part.

  7. #6
    bisou10

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    Enfin un logcat ! Maintenant que c'est un peu plus précis, je réponds.

    La dernière fois que j'ai eu cette erreur, j'ai du déployer mon code dans une AsyncTask, car tu ne peux pas faire de la communication sur la main Activity.

    Après, 2 secondes de recherche sur l'exception levée et tu as ta réponse... https://stackoverflow.com/questions/...rkonmainthread

  8. #7
    chahbane

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    Merci bcp Bisou10 ca marche avec l'asyncTask mais j'ai un autre probleme maintenant. L'application Android doit toujours etre en attente d'un packet (dans une boucle infinie) et en meme temps je veux la manipuler, pour par exemple envoyer une autre donnee sur le reseau en cliquant sur un bouton.
    c'est comme si j'ai un processus "EcouterReseau" et si je clique sur un bouton, un autre processus plus prioritaire doit s'executer.
    Est ce que vous avez une idee comment je pourrai faire ca??

  9. #8
    bisou10

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    Pareil, mettre la partie ecoute dans une autre Asynctask ou un Thread (vas-y en Runnable()). Ainsi tu ne bloques pas ton Thread UI.

    Moi perso je travaille souvent avec des Handler() pour avoir accès aux ressources du thread UI, et effectuer des actions récurrentes. Mais a toi de voir.
    Dernière modification par bisou10 ; 04/05/2014 à 08h23.

  10. #9
    polo974

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    En c ou en python, il y a select().
    en java, il y a un truc qui s'appelle Selector qui permet d'éviter d'ouvrir un thread pour un oui ou pour un non (pour économiser les ressources)...
    bon, ensuite, le thread en question risque de devenir un fourre-tout kilométrique et illisible...
    Jusqu'ici tout va bien...

  11. #10
    chahbane

    Re : Connexion par socket entre smartphone Android et application Java sur PC

    Monsieur, j'ai essaye de travailler avec les handlers mais j'ai quelques problemes bien avant l'utilisation du handler. Je suis en train de realiser mon projet de fin d'etudes et je suis totalement débordé. je vous remercie pour votre aide.
    c'est mon nouveau code :

    Code:
    package com.dsz.tcpserverandr;
    
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.widget.TextView;
    
    public class TCPServerAndr extends Activity 
    {
     	Thread serverThread;
     	private TextView text;
     	public static final int SERVERPORT = 11111;
    	 ServerSocket echoServer;
         String line;
         DataInputStream is;
         PrintStream os;
         Socket clientSocket;	
    	 Handler hand;
         
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		serverThread = null; 
    		ServerSocket echoServer = null;
    	    Socket clientSocket = null;
    		hand = new Handler();
    		text = (TextView) findViewById(R.id.textView1);
    		this.serverThread = new Thread(new ServerThread());
    		this.serverThread.start();
    	}
    	
    	@Override
    	protected void onStop() {
    		super.onStop();
    		try {
    			echoServer.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	class ServerThread implements Runnable {
    
    		public void run() 
    		{
    			//Socket socket = null;
    			try 
    	        {
    	           echoServer = new ServerSocket(SERVERPORT);
    	           System.out.println("listening");
    	        }
    	        catch (IOException e) 
    	        {
    	           System.out.println(e);
    	        } 
    			
    			try 
        	    {
        	           clientSocket = echoServer.accept();
        	           is = new DataInputStream(clientSocket.getInputStream());
        	           os = new PrintStream(clientSocket.getOutputStream());
        	           while (true) 
        	           {
        	             if ((line=is.readLine())!=null)
        	             {
        	            	System.out.println("received : "+line);
        	            	hand.post(new updateIHM(line));
        	             }
        	           }
        	           
        	        }   
        	    catch (IOException e) 
        	    {
        	    	System.out.println("prob");
        	        System.out.println(e);
        	    }
    			
    		}
    	}
          
    	
    	class updateIHM implements Runnable {
    		private String msg;
    
    		public updateIHM(String str) {
    			this.msg=str;
    			
    		}
    
    		@Override
    		public void run() {
    			text.setText(msg);
    		}
    	}
    	
    }
    le logcat est plein d'erreurs :/
    Fichiers attachés Fichiers attachés

Discussions similaires

  1. Concaténation/Couleur java android
    Par pichnochio dans le forum Programmation et langages, Algorithmique
    Réponses: 2
    Dernier message: 11/12/2011, 15h52
  2. Developpement d'application Smartphone (Android)
    Par invited73295ef dans le forum Logiciel - Software - Open Source
    Réponses: 2
    Dernier message: 03/10/2011, 15h15
  3. socket en java
    Par invite055c7a42 dans le forum Internet - Réseau - Sécurité générale
    Réponses: 4
    Dernier message: 07/07/2006, 20h40