具有多个Android客户端的服务器

时间:2011-04-13 08:56:10

标签: android

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.*;
import java.net.*;

public class MainActivity extends Activity implements Runnable {

    TextView tview;
    BufferedReader in;
    Socket socket;
    private LocationManager lm;
    private LocationListener locationListener;

    Thread thread = new Thread();
    /** Called when the activity is first created. */
    @Override
    public void run()
    {
        try
        {
            socket = new Socket("10.0.2.2", 1234);
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            out.println("Connection Established");

        }
        catch (Exception e)
        { 
            tview.setText(e.toString());
        }

        try 
        { 
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        }
        catch (Exception e)
        { 
            tview.setText(e.toString());
        }

        try
        {
            String line = in.readLine();
        } 
        catch (IOException e) 
        {
             System.exit(-1);
        }
    }

    public void onCreate(Bundle savedInstanceState) {

        thread.start();

        tview = new TextView(this);    


        setContentView(tview);
        super.onCreate(savedInstanceState);

        lm = (LocationManager) 
        getSystemService(Context.LOCATION_SERVICE);    

        locationListener = new MyLocationListener();

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);  



    }

    private class MyLocationListener implements LocationListener 
    {
        @Override
        public void onLocationChanged(Location loc) {

        if (loc != null) {

                PrintWriter out;

                try 
                {
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                    out.println("Location~"+loc.getLongitude()+"~"+loc.getLatitude());//change this with location!!!!!!!!
                }
                catch (IOException e)
                {

                    e.printStackTrace();
                }

                Toast.makeText(getBaseContext()," Locationchanged : Lat: " + loc.getLatitude() + 
                    " Lng:  " + loc.getLongitude(), 
                    Toast.LENGTH_SHORT).show();

                try
                {
                    String line = in.readLine();
                } 
                catch (Exception e)
                {
                    System.out.println("reading  failed");
                }

            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, 
            Bundle extras) {
            // TODO Auto-generated method stub
        }
    }        


}

Log cat:

    04-13 13:09:52.303: DEBUG/dalvikvm(425): GC freed 43 objects / 1960 bytes in 155ms
04-13 13:22:34.983: DEBUG/AndroidRuntime(691): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
04-13 13:22:34.994: DEBUG/AndroidRuntime(691): CheckJNI is ON
04-13 13:22:35.353: DEBUG/AndroidRuntime(691): --- registering native functions ---
04-13 13:22:35.413: INFO/jdwp(691): Ignoring second debugger -- accepting and dropping
04-13 13:22:35.422: INFO/jdwp(691): Ignoring second debugger -- accepting and dropping
04-13 13:22:35.943: DEBUG/ddm-heap(691): Got feature list request
04-13 13:22:36.593: DEBUG/PackageParser(275): Scanning package: /data/app/vmdl34515.tmp
04-13 13:22:36.723: INFO/PackageManager(275): Removing non-system package:com.servertest
04-13 13:22:36.734: DEBUG/PackageManager(275): Removing package com.servertest
04-13 13:22:36.744: DEBUG/PackageManager(275):   Activities: com.servertest.MainActivity
04-13 13:22:36.883: DEBUG/PackageManager(275): Scanning package com.servertest
04-13 13:22:36.892: INFO/PackageManager(275): /data/app/vmdl34515.tmp changed; unpacking
04-13 13:22:36.913: DEBUG/installd(32): DexInv: --- BEGIN '/data/app/vmdl34515.tmp' ---
04-13 13:22:37.242: DEBUG/dalvikvm(697): DexOpt: load 53ms, verify 86ms, opt 2ms
04-13 13:22:37.272: DEBUG/installd(32): DexInv: --- END '/data/app/vmdl34515.tmp' (success) ---
04-13 13:22:37.282: DEBUG/PackageManager(275):   Activities: com.servertest.MainActivity
04-13 13:22:37.293: DEBUG/ActivityManager(275): Uninstalling process com.servertest
04-13 13:22:37.432: INFO/installd(32): move /data/dalvik-cache/data@app@vmdl34515.tmp@classes.dex -> /data/dalvik-cache/data@app@com.servertest.apk@classes.dex
04-13 13:22:37.453: DEBUG/PackageManager(275): New package installed in /data/app/com.servertest.apk
04-13 13:22:37.602: DEBUG/AndroidRuntime(691): Shutting down VM
04-13 13:22:37.612: DEBUG/dalvikvm(691): DestroyJavaVM waiting for non-daemon threads to exit
04-13 13:22:37.633: DEBUG/dalvikvm(691): DestroyJavaVM shutting VM down
04-13 13:22:37.633: DEBUG/dalvikvm(691): HeapWorker thread shutting down
04-13 13:22:37.643: DEBUG/dalvikvm(691): HeapWorker thread has shut down
04-13 13:22:37.643: DEBUG/jdwp(691): JDWP shutting down net...
04-13 13:22:37.653: INFO/dalvikvm(691): Debugger has detached; object registry had 1 entries
04-13 13:22:37.663: DEBUG/dalvikvm(691): VM cleaning up
04-13 13:22:37.682: ERROR/AndroidRuntime(691): ERROR: thread attach failed
04-13 13:22:37.713: DEBUG/ActivityManager(275): Uninstalling process com.servertest
04-13 13:22:37.763: DEBUG/dalvikvm(691): LinearAlloc 0x0 used 623916 of 5242880 (11%)
04-13 13:22:37.993: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f0700e5
04-13 13:22:38.033: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f020031
04-13 13:22:38.033: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f020030
04-13 13:22:38.044: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f050000
04-13 13:22:38.253: DEBUG/dalvikvm(322): GC freed 2620 objects / 147200 bytes in 287ms
04-13 13:22:38.343: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f060000
04-13 13:22:38.443: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f060001
04-13 13:22:38.554: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f0700e5
04-13 13:22:38.573: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f020031
04-13 13:22:38.573: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f020030
04-13 13:22:38.573: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f050000
04-13 13:22:38.593: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f060000
04-13 13:22:38.613: WARN/ResourceType(275): Resources don't contain package for resource number 0x7f060001
04-13 13:22:39.083: DEBUG/dalvikvm(275): GC freed 13508 objects / 833920 bytes in 393ms
04-13 13:22:40.073: DEBUG/AndroidRuntime(702): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
04-13 13:22:40.093: DEBUG/AndroidRuntime(702): CheckJNI is ON
04-13 13:22:40.683: DEBUG/AndroidRuntime(702): --- registering native functions ---
04-13 13:22:40.733: INFO/jdwp(702): Ignoring second debugger -- accepting and dropping
04-13 13:22:41.233: INFO/jdwp(702): Ignoring second debugger -- accepting and dropping
04-13 13:22:41.243: DEBUG/ddm-heap(702): Got feature list request
04-13 13:22:41.983: INFO/ActivityManager(275): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.servertest/.MainActivity }
04-13 13:22:42.143: DEBUG/AndroidRuntime(702): Shutting down VM
04-13 13:22:42.143: DEBUG/dalvikvm(702): DestroyJavaVM waiting for non-daemon threads to exit
04-13 13:22:42.153: DEBUG/dalvikvm(702): DestroyJavaVM shutting VM down
04-13 13:22:42.153: DEBUG/dalvikvm(702): HeapWorker thread shutting down
04-13 13:22:42.163: DEBUG/dalvikvm(702): HeapWorker thread has shut down
04-13 13:22:42.163: DEBUG/jdwp(702): JDWP shutting down net...
04-13 13:22:42.163: INFO/dalvikvm(702): Debugger has detached; object registry had 1 entries
04-13 13:22:42.183: DEBUG/dalvikvm(702): VM cleaning up
04-13 13:22:42.223: INFO/ActivityManager(275): Start proc com.servertest for activity com.servertest/.MainActivity: pid=709 uid=10029 gids={3003}
04-13 13:22:42.233: ERROR/AndroidRuntime(702): ERROR: thread attach failed
04-13 13:22:42.333: DEBUG/dalvikvm(702): LinearAlloc 0x0 used 639500 of 5242880 (12%)
04-13 13:22:42.593: DEBUG/dalvikvm(270): GC freed 299 objects / 11584 bytes in 352ms
04-13 13:22:42.713: INFO/jdwp(709): Ignoring second debugger -- accepting and dropping
04-13 13:22:42.713: INFO/jdwp(709): Ignoring second debugger -- accepting and dropping
04-13 13:22:42.823: DEBUG/ddm-heap(709): Got feature list request
04-13 13:22:42.943: DEBUG/dalvikvm(270): GC freed 57 objects / 2432 bytes in 299ms
04-13 13:22:43.163: DEBUG/dalvikvm(270): GC freed 2 objects / 56 bytes in 215ms
04-13 13:22:43.613: DEBUG/LocationManager(709): Constructor: service = android.location.ILocationManager$Stub$Proxy@44e944b0
04-13 13:22:43.633: WARN/GpsLocationProvider(275): Duplicate add listener for uid 10029
04-13 13:22:43.643: DEBUG/GpsLocationProvider(275): setMinTime 0
04-13 13:22:43.643: DEBUG/GpsLocationProvider(275): startNavigating
04-13 13:22:44.003: INFO/ActivityManager(275): Displayed activity com.servertest/.MainActivity: 1884 ms (total 2046680 ms)
04-13 13:22:49.213: DEBUG/dalvikvm(322): GC freed 2508 objects / 143160 bytes in 115ms
04-13 13:22:54.343: DEBUG/dalvikvm(425): GC freed 80 objects / 3880 bytes in 171ms
04-13 13:23:02.119: DEBUG/GpsLocationProvider(275): TTFF: 18468
04-13 13:23:02.133: DEBUG/AndroidRuntime(709): Shutting down VM
04-13 13:23:02.143: WARN/dalvikvm(709): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-13 13:23:02.154: ERROR/AndroidRuntime(709): Uncaught handler: thread main exiting due to uncaught exception
04-13 13:23:02.183: ERROR/AndroidRuntime(709): java.lang.NullPointerException
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at com.servertest.MainActivity$MyLocationListener.onLocationChanged(MainActivity.java:93)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:179)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:112)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:128)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at android.os.Looper.loop(Looper.java:123)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at android.app.ActivityThread.main(ActivityThread.java:4363)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at java.lang.reflect.Method.invokeNative(Native Method)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at java.lang.reflect.Method.invoke(Method.java:521)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-13 13:23:02.183: ERROR/AndroidRuntime(709):     at dalvik.system.NativeStart.main(Native Method)
04-13 13:23:02.205: INFO/Process(275): Sending signal. PID: 709 SIG: 3
04-13 13:23:02.223: INFO/dalvikvm(709): threadid=7: reacting to signal 3
04-13 13:23:02.253: INFO/dalvikvm(709): Wrote stack trace to '/data/anr/traces.txt'
04-13 13:23:05.785: INFO/Process(709): Sending signal. PID: 709 SIG: 9
04-13 13:23:05.833: INFO/ActivityManager(275): Process com.servertest (pid 709) has died.
04-13 13:23:05.843: WARN/GpsLocationProvider(275): Unneeded remove listener for uid 1000
04-13 13:23:05.843: DEBUG/GpsLocationProvider(275): stopNavigating
04-13 13:23:05.903: INFO/WindowManager(275): WIN DEATH: Window{44d4f370 com.servertest/com.servertest.MainActivity paused=false}
04-13 13:23:06.074: INFO/UsageStats(275): Unexpected resume of com.android.launcher while already resumed in com.servertest
04-13 13:23:06.153: WARN/InputManagerService(275): Got RemoteException sending setActive(false) notification to pid 709 uid 10029

更新

我仍然无法从服务器写入客户端。就目前而言,通信只是一种方式,从客户端到服务器。因为我多次尝试没有成功,我不知道我做错了什么。任何帮助将不胜感激。这是我的代码:

服务器类:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerClass implements Runnable {


   private int ID;
   public String line;

   PrintWriter out = null;
   private Socket connection;

     public static void main(String[] args)
     {

         int port = 1234;
         int count = 0;

         try
         {
             ServerSocket serverSocket = new ServerSocket(port);
             System.out.println("Server Initialized");
             while (true)
             {
                 Socket connection = serverSocket.accept();
                 Runnable runnable = new NewClass1(connection, ++count);
                 Thread thread = new Thread(runnable);
                 thread.start();
             }
         }
         catch (Exception e)
         {
             System.out.println("opening socket failed");
         }
     }




     ServerClass(Socket s, int i)
     {
         this.connection = s;
         this.ID=i;

     }

     public void run()
     {
         //String line;
         BufferedReader in = null;

         try
         {
            in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            out = new PrintWriter(connection.getOutputStream());
         }
         catch(Exception e)
         {
             System.out.println("Readers and Writers failed");
             System.exit(-1);
         }

         while(true)
         {
             try
             {
                 line = in.readLine();
                 out.println("Success");

                 System.out.println(line);

             }
             catch(Exception e)
             {
                 System.out.println("Failed");
             }
         }
     }
}

和Android活动:

package com.servertest;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.*;
import java.net.*;

public class MainActivity extends Activity {

    TextView tview;
    BufferedReader in;
    Socket socket;
    private LocationManager lm;
        private LocationListener locationListener;

    static int portnumber = 1234;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        tview = new TextView(this);    
        new Thread()
        {
         public void run()
            {   
                try
                {
                    socket = new Socket("10.0.2.2", portnumber);

                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                    out.println("Connection  Established");

                }
                catch (Exception e)
                { 
                    tview.setText(e.toString());
                }


            }
        }.start();


        setContentView(tview);
        super.onCreate(savedInstanceState);

        lm = (LocationManager) 
        getSystemService(Context.LOCATION_SERVICE);    

        locationListener = new MyLocationListener();

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);  

    }

    private class MyLocationListener implements LocationListener 
    {


        @Override
        public void onLocationChanged(Location loc) {

        if (loc != null) {

                PrintWriter out;

    try 
        {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                    out.println("Location test");

                }
                catch (IOException e)
                {

                    e.printStackTrace();
                }



                Toast.makeText(getBaseContext()," Locationchanged : Lat: " + loc.getLatitude() + 
                    " Lng:  " + loc.getLongitude(), 
                    Toast.LENGTH_SHORT).show();

                try
                {

                    String line = in.readLine();
                    Log.v("readLine success", line);

                  Toast.makeText(getBaseContext(),line,Toast.LENGTH_SHORT).show();

                } 
                catch (Exception e)
                {
                    Log.v("readline","failed");
                }

            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, 
            Bundle extras) {
            // TODO Auto-generated method stub
        }
    }  
}

1 个答案:

答案 0 :(得分:1)

我认为问题可能是,网络通信和LocationListener都在UIThread上运行并相互阻塞。在另一个线程中与服务器进行通信,并且LocationListener应该再次工作。