android socket客户端/服务器断开连接

时间:2014-09-17 18:35:40

标签: java android sockets

我正在为Android编写一个简单的客户端服务器,它在我重新启动客户端之前一直工作。然后什么都没发生服务器连续运行,客户端必须连接和断开连接。任何一些帮助都会非常有用。谢谢。

服务器

public class MyService extends Service {

 String line = null;
    String temp_comand = null;
    Socket client;

    public static String SERVERIP = "10.0.2.15";
    public final static int DISPATCH_KEY_FROM_IME = 1011;

    public static final int SERVERPORT = 8080;

    private Handler handler = new Handler();

    private ServerSocket serverSocket;

@Override
public IBinder onBind(Intent intent) {

    return null;
}

@Override
public void onCreate() {
    Log.i("SERVISE", "STARTED");

      SERVERIP = getLocalIpAddress();

        Thread fst = new Thread(new ServerThread());
        fst.start();

}


 public class ServerThread implements Runnable {

        public void run() {
            try {
                if (SERVERIP != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            Log.v("wlan0", Utils.getMACAddress("wlan0"));
                            Log.v("eth0", Utils.getMACAddress("eth0"));
                            Log.v("<< IP4 >>", Utils.getIPAddress(true)); 
                            Log.v("<< IP6 >>", Utils.getIPAddress(false));
                        }
                    });
                    serverSocket = new ServerSocket(SERVERPORT);
                    while (true) {
                        // LISTEN FOR INCOMING CLIENTS
                        client = serverSocket.accept();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {


                            }
                        });

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

                            while ((line = in.readLine()) != null) {
                                Log.d("ServerActivity", line);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {


                                        if (line.equals("next")){
                                            simulateKey(22);

                                        }
                                            if (line.equals("beack")){
                                            simulateKey(21);

                                        }
                                            if (line.equals("up")){
                                            simulateKey(19);

                                        }
                                            if (line.equals("down")){
                                            simulateKey(20);

                                        }
                                            if (line.equals("ok")){
                                            simulateKey(23);

                                        }
                                            if (line.equals("power")){
                                            simulateKey(170);

                                        }
                                            if (line.equals("exit")){
                                            simulateKey(4);

                                        }
                                            if (line.equals("vol_m")){
                                            simulateKey(25);

                                        }
                                            if (line.equals("vol_up")){
                                            simulateKey(24);

                                        }
                                            if (line.equals("menu")){
                                            simulateKey(82);

                                        }
                                            if (line.equals("left")){
                                            simulateKey(88);

                                        }
                                            if (line.equals("right")){
                                            simulateKey(87);

                                        }
                                            if (line.equals("home")){
                                                simulateKey(3);

                                            }
                                            if (line.equals("close")){
                                                simulateKey(4);

                                            }


                                          //  Log.d("ServerActivity", line);

                                    }
                                });
                            }
                            break;
                        } catch (Exception e) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {

                                }
                            });
                            e.printStackTrace();
                        }
                    }
                } else {
                    handler.post(new Runnable() {
                        @Override
                       public void run() {
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
                e.printStackTrace();
            }
        }
    }

    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
                }
            }
        } catch (SocketException ex) {
            Log.e("ServerActivity", ex.toString());
        }
        return null;
    }






    public  void simulateKey(final int KeyCode) {

        new Thread() {
            @Override
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(KeyCode);
               } catch (Exception e) {
                    Log.e("Exception when sendKeyDownUpSync", e.toString());
                }
            }

        }.start();
    }



       }

客户端

public class ClientActivity extends Activity {


String comand = "Жду команду";
private Button  right, left, up, dn, menu, pow, min, plus, ok, sw_l, sw_r, close, home;

private String serverIpAddress = "";
 String serverIp;
 Socket socket;
private boolean connected = false;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.client);







    final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
    final DhcpInfo dhcp = manager.getDhcpInfo();
    serverIp = Formatter.formatIpAddress(dhcp.gateway);

    if (!connected) {
        serverIpAddress = serverIp;
        if (!serverIpAddress.equals("")) {
            Thread cThread = new Thread(new ClientThread());
            cThread.start();
        }
    }



    right = (Button) findViewById(R.id.btn_right);
    left = (Button) findViewById(R.id.btn_left);
    up= (Button) findViewById(R.id.btn_up);
    dn= (Button) findViewById(R.id.btn_dn);
    menu= (Button) findViewById(R.id.btn_menu);
    pow= (Button) findViewById(R.id.btn_pow);
    min= (Button) findViewById(R.id.btn_min);
    plus= (Button) findViewById(R.id.btn_plus);
    ok= (Button) findViewById(R.id.btn_ok);
    sw_l= (Button) findViewById(R.id.btn_sw_left);
    sw_r= (Button) findViewById(R.id.btn_sw_rig);
    close = (Button) findViewById(R.id.btn_close);
    home= (Button) findViewById(R.id.btn_home);

    Log.e("KeyEvent.KEYCODE_HOME", String.valueOf(KeyEvent.KEYCODE_HOME));




    right.setOnClickListener(new View.OnClickListener() {
     @Override
        public void onClick(View v) {
        comand = "next";
     }});

    left.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            comand = "beack";
     }});
     up.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        comand = "up";
 }});
     dn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        comand = "down";
 }});
     menu.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
    comand = "menu";
 }});
     pow.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
    comand = "power";
 }});
     min.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
    comand = "vol_m";
 }});
     plus.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
    comand = "vol_up";
 }});
     ok.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
    comand = "ok";
 }});
     sw_l.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
    comand = "left";
 }});
    sw_r.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
    comand = "right";
 }});

        home.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        comand = "home";
     }});
           close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        comand = "close";
     }});

}






public class ClientThread implements Runnable {

    public void run() {

        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            socket = new Socket(serverAddr, 8080);

            connected = true;
            while (connected) {
                try {

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

                    if(out.checkError())
                    {Log.d("ClientActivity", "Error transmitting data");
                        throw new Exception("Error transmitting data.");
                    }  


                        if (comand.equals("next")){
                        out.println(comand);
                        comand = "Жду";
                    }
                        if (comand.equals("beack")){
                            out.println(comand);
                            comand = "Жду";
                    }
                        if (comand.equals("up")){
                        out.println(comand);
                        comand = "Жду";
                    }
                        if (comand.equals("down")){
                        out.println(comand);
                        comand = "Жду";
                    }
                         if (comand.equals("ok")){
                         out.println(comand);
                         comand = "Жду";
                    }
                         if (comand.equals("power")){
                         out.println(comand);
                         comand = "Жду";
                    }
                         if (comand.equals("exit")){
                         out.println(comand);
                         comand = "Жду";
                    }
                          if (comand.equals("vol_m")){
                          out.println(comand);
                          comand = "Жду";
                    }
                          if (comand.equals("vol_up")){
                          out.println(comand);
                          comand = "Жду";
                    }
                          if (comand.equals("menu")){
                          out.println(comand);
                          comand = "Жду";
                    }
                         if (comand.equals("left")){
                          out.println(comand);
                          comand = "Жду";
                    }
                          if (comand.equals("right")){
                          out.println(comand);
                          comand = "Жду";
                    }
                          if (comand.equals("home")){
                              out.println(comand);
                              comand = "Жду";
                        }
                          if (comand.equals("close")){
                              out.println(comand);
                              comand = "Жду";
                        }




                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;

        }






    }
}

protected String wifiIpAddress(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();

    // Convert little-endian to big-endianif needed
    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
        ipAddress = Integer.reverseBytes(ipAddress);
    }

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();

    String ipAddressString;
    try {
        ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
        Log.e("WIFIIP", "Unable to get host address.");
        ipAddressString = null;
    }

    return ipAddressString;
}


}

1 个答案:

答案 0 :(得分:0)

如果客户端没有断开连接,则服务器停留在此循环中:while ((line = in.readLine()) != null)等待并等待下一行。同时没有其他客户端可以连接。