IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Android Discussion :

socket + service à l'ecoute des evenements provenant du serveur


Sujet :

API standards et tierces Android

  1. #1
    Membre régulier
    Inscrit en
    Décembre 2008
    Messages
    233
    Détails du profil
    Informations personnelles :
    Âge : 37

    Informations forums :
    Inscription : Décembre 2008
    Messages : 233
    Points : 73
    Points
    73
    Par défaut socket + service à l'ecoute des evenements provenant du serveur
    bonjour,
    je veux ouvrir une session entre un client (telephone) et un serveur web, la c'est bon il suffit d'utiliser une socket mais mon problème c'est que je veux que le client soit à l'ecoute de tout evenement du serveur c'est a dire je dois implémenter un listener (dès que le serveur notifie le client que le fichier x est pret pour le téléchargement, le client le télécharge dans l'immédiat (je souligne la contrainte temps reel)) c'est pour ça je compte faire un service qui fera la tache de l'ecoute des evenements provenants du serveur le hic, primo je sais pas si c'est vraiment faisable (peut etre un web service convient mieux ) secondo je sais pas comment je peux combiner entre socket et service, voici le code de ma socket (TCP)

    l'activité
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.e2esp.socket.test;
     
    import android.app.Activity;
    import android.os.Bundle;
     
    public class SocketTest extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
     
            Thread cThread = new Thread(new TCPClient());
     
             cThread.start();
     
        }
    }
    client:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    package com.e2esp.socket.test;
     
    import java.io.BufferedWriter;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
     
    import android.util.Log;
     
    public class TCPClient implements Runnable {
     
     
        public void run() {
             try {
     
            	 InetAddress serverAddr = InetAddress.getByName("192.168.1.2");//TCPServer.SERVERIP
     
            	 Log.d("TCP", "C: Connecting...");
            	 Socket socket = new Socket(serverAddr, TCPDesktopServer.SERVERPORT);
            	 String message = "Hello from Client";
    		     try {
    		    	 Log.d("TCP", "C: Sending: '" + message + "'");
    		    	 PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
     
    		    	 out.println(message);
    		    	 Log.d("TCP", "C: Sent.");
    	             Log.d("TCP", "C: Done.");
     
                 } catch(Exception e) {
                     Log.e("TCP", "S: Error", e);
    		      } finally {
    		        socket.close();
    		      }
             } catch (Exception e) {
                  Log.e("TCP", "C: Error", e);
             }
        }
    }
    serveur:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    package com.e2esp.socket.test;
     
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
     
    public class TCPDesktopServer implements Runnable{
     
        public static final String SERVERIP = "127.0.0.1";
        public static final int SERVERPORT =80 ; //4444
     
        public void run() {
             try {
            	 System.out.println("S: Connecting...");
     
                 ServerSocket serverSocket = new ServerSocket(SERVERPORT);
                 while (true) {
     
                	  Socket client = serverSocket.accept();
                	  System.out.println("S: Receiving...");
     
                	  try {
                          BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                          String str = in.readLine();
                          System.out.println("S: Received: '" + str + "'");
                        } catch(Exception e) {
                            System.out.println("S: Error");
                            e.printStackTrace();
                        } finally {
                        	client.close();
                            System.out.println("S: Done.");
                        }
     
                 }
     
             } catch (Exception e) {
                 System.out.println("S: Error");
                 e.printStackTrace();
             }
        }
     
        public static void main (String a[]) {
        	Thread desktopServerThread = new Thread(new TCPDesktopServer());
        	desktopServerThread.start();
        }
    }
    merci d'avance pour tout aide

  2. #2
    Modérateur
    Avatar de dinobogan
    Homme Profil pro
    ingénieur
    Inscrit en
    Juin 2007
    Messages
    4 073
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France

    Informations professionnelles :
    Activité : ingénieur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 4 073
    Points : 7 163
    Points
    7 163
    Par défaut
    Citation Envoyé par perloutta Voir le message
    je veux que le client soit à l'ecoute de tout evenement du serveur c'est a dire je dois implémenter un listener (dès que le serveur notifie le client que le fichier x est pret pour le téléchargement, le client le télécharge dans l'immédiat (je souligne la contrainte temps reel))
    Tu viens de décrire le fonctionnement client-serveur... mais à l'envers.
    Ton client doit devenir serveur, et ton serveur doit devenir client. Tu auras ainsi du "temps réel".
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java
    Que la force de la puissance soit avec le courage de ta sagesse.

  3. #3
    Membre régulier
    Inscrit en
    Décembre 2008
    Messages
    233
    Détails du profil
    Informations personnelles :
    Âge : 37

    Informations forums :
    Inscription : Décembre 2008
    Messages : 233
    Points : 73
    Points
    73
    Par défaut
    oui un peu ça...mais de point de vue technique est ce que un service fera l'affaire?

  4. #4
    Membre régulier
    Inscrit en
    Décembre 2008
    Messages
    233
    Détails du profil
    Informations personnelles :
    Âge : 37

    Informations forums :
    Inscription : Décembre 2008
    Messages : 233
    Points : 73
    Points
    73
    Par défaut
    re bonjour!!
    bon j'ai essayé autrement en s'inspirant de ce tutorial http://developerlife.com/tutorials/?p=356
    et de l'api demo j'ai réalisé ce service :

    service:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    /*
     * Copyright (C) 2007 The Android Open Source Project
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
     
    package com.exemple.localService;
     
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Timer;
    import java.util.TimerTask;
     
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
     
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.Intent;
    import android.graphics.drawable.Drawable;
    import android.os.Binder;
    import android.os.IBinder;
    import android.util.Log;
    import android.widget.Toast;
     
    /**
     * This is an example of implementing an application service that runs locally
     * in the same process as the application.  The {@link LocalServiceController}
     * and {@link LocalServiceBinding} classes show how to interact with the
     * service.
     *
     * <p>Notice the use of the {@link NotificationManager} when interesting things
     * happen in the service.  This is generally how background services should
     * interact with the user, rather than doing something more disruptive such as
     * calling startActivity().
     */
    public class LocalService extends Service {
        private NotificationManager mNM;
        private Timer timer = new Timer();
        private static final long UPDATE_INTERVAL = 5000;
        private final String TAG="service";
        //public static ServiceUpdateUIListener UI_UPDATE_LISTENER;
        private static LocalServiceController MAIN_ACTIVITY;
    public String url="http://10.0.2.2/imageTest.jpeg";
        /**
         * Class for clients to access.  Because we know this service always
         * runs in the same process as its clients, we don't need to deal with
         * IPC.
         */
        public class LocalBinder extends Binder {
            LocalService getService() {
                return LocalService.this;
            }
        }
     
        @Override
        public void onCreate() {
            mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
     
            // Display a notification about us starting.  We put an icon in the status bar.
            showNotification();
     
            // init the service here
            _startService();
            if (MAIN_ACTIVITY != null)
            {Toast msg = Toast.makeText(LocalService.this, " MyService started ", Toast.LENGTH_LONG);
          	  msg.show();}
        }
     
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;
        }
     
        @Override
        public void onDestroy() {
            // Cancel the persistent notification.
            mNM.cancel(R.string.local_service_started);
            _shutdownService();
     
     
             if (MAIN_ACTIVITY != null) 
            // Tell the user we stopped.
            Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
        }
     
        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }
     
        // This is the object that receives interactions from clients.  See
        // RemoteService for a more complete example.
        private final IBinder mBinder = new LocalBinder();
     
        /**
         * Show a notification while this service is running.
         */
        private void showNotification() {
            // In this sample, we'll use the same text for the ticker and the expanded notification
            CharSequence text = getText(R.string.local_service_started);
     
            // Set the icon, scrolling text and timestamp
            Notification notification = new Notification(R.drawable.stat_sample, text,
                    System.currentTimeMillis());
     
            // The PendingIntent to launch our activity if the user selects this notification
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, LocalServiceController.class), 0);
     
            // Set the info for the views that show in the notification panel.
            notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                           text, contentIntent);
     
            // Send the notification.
            // We use a layout id because it is a unique number.  We use it later to cancel.
            mNM.notify(R.string.local_service_started, notification);
        }
     
     
        private void _startService() {
        	  timer.scheduleAtFixedRate(
        	      new TimerTask() {
     
        	        public void run() {
        	          _getData(url);
        	        }
     
     
        	      },
        	      0,
        	      UPDATE_INTERVAL);
        	  Log.i(getClass().getSimpleName(), "Timer started!!!");
        	}
     
     
     
     
     
        private void _shutdownService() {
        	  if (timer != null) timer.cancel();
        	  Log.i(getClass().getSimpleName(), "Timer stopped!!!");
        	}
     
     
     
     
        private void _getData(String url) {
     
        	InputStream content = null;
     
        	try {
          		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httpPost = new HttpPost(url);
    		List nameValuePairs = new ArrayList(1);
                        //this is where you add your data to the post method
                        nameValuePairs.add(new BasicNameValuePair("name", "anthony"));
    		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		// Execute HTTP Post Request
    		HttpResponse response = httpclient.execute(httpPost);
    		content = response.getEntity().getContent();
     
     
    	    Log.i(getClass().getSimpleName(), "data size from servlet=" + content.toString());
     
    	        //return content;
            }catch (Exception e) {
    			//handle the exception !
            	Log.d(TAG,e.getMessage());
     
    		}
     
     
     
    	}
     
     
     
    }
    activité appelant ce service:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    package com.exemple.localService;
     
    // Need the following import to get access to the app resources, since this
    // class is in a sub-package.
     
    import com.exemple.localService.R;
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
     
     
    /**
     * <p>Example of explicitly starting and stopping the {@link LocalService}.
     * This demonstrates the implementation of a service that runs in the same
     * process as the rest of the application, which is explicitly started and stopped
     * as desired.</p>
     */
    public class LocalServiceController extends Activity {
    	private final String TAG="service";
    	private ImageView imgView;
        @Override
    	protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
     
            setContentView(R.layout.local_service_controller);
     
            // Watch for button clicks.
            Button button = (Button)findViewById(R.id.start);
            button.setOnClickListener(mStartListener);
            button = (Button)findViewById(R.id.stop);
            button.setOnClickListener(mStopListener);
            imgView=(ImageView)findViewById(R.id.ImageView01);
        }
     
        private OnClickListener mStartListener = new OnClickListener() {
            public void onClick(View v)
            {
                // Make sure the service is started.  It will continue running
                // until someone calls stopService().  The Intent we use to find
                // the service explicitly specifies our service component, because
                // we want it running in our own process and don't want other
                // applications to replace it.
                try{
            	startService(new Intent(LocalServiceController.this,
                        LocalService.class));
     
     
     
     
    	    }
     
     
    	  catch (Exception e) {
    	    Log.e(TAG, "ui creation problem", e);
    	  }
            }
        };
     
        private OnClickListener mStopListener = new OnClickListener() {
            public void onClick(View v)
            {
                // Cancel a previous call to startService().  Note that the
                // service will not actually stop at this point if there are
                // still bound clients.
                stopService(new Intent(LocalServiceController.this,
                        LocalService.class));
            }
        };
    }
    c'est pas une version finalisée parce que je l'ai faite pour un simple test
    mais sincérement je la trouve pas idéale, c'est pas pratique d'envoyer des requetes au serveur tout les 5 secondes!!! j'ai pas trouvé autre alternative

    pouvez vous me renseigner svp quelques idées??
    merci

Discussions similaires

  1. affichage des données provenant d'un web service soap dans une listview
    Par nagca dans le forum API standards et tierces
    Réponses: 1
    Dernier message: 04/07/2011, 17h11
  2. service WCF avec opérations asynchrone basée sur des evenements
    Par Yogy dans le forum Windows Communication Foundation
    Réponses: 5
    Dernier message: 10/12/2009, 19h21
  3. Réponses: 9
    Dernier message: 12/11/2008, 10h45
  4. [VB6] Interception des évènement Copier/Couper/Coller
    Par youtch dans le forum VB 6 et antérieur
    Réponses: 5
    Dernier message: 18/10/2002, 17h09

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo