The next; Android Socket instance (2) file list dynamic access

This content: use socket technology to enable Android to access the computer directory, and return the results to android.

Train of thought:

The Android server is responsible for writing and passing specified commands to the server through the underlying design when the user triggers specified events.

After the server of IDEA is started, it is responsible for parsing and processing the data flow commands from android terminal in real time and returning the running results.

Idea server code:

package lrz.server; import java.io.*; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; public class ServerSocket01 { int port = 8019; / / a custom port, the port number as far as possible choose a few not occupied by other service port, see http://blog.csdn.net/hsj521li/article/details/7678880 static int connect_count = 0; ArrayList<String> msgBackList; public ServerSocket01() { // TODO Auto-generated constructor stub } public ServerSocket01(int port) { super(); this.port = port; } private void printLocalIp(ServerSocket ServerSocket) {// Enumerate the IP address of the print server try {system.out. println(" Server command port prot=" + serverSocket.getLocalPort()); Enumeration<NetworkInterface> interfaces = null; interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); Enumeration<InetAddress> addresss = ni.getInetAddresses(); while (addresss.hasMoreElements()) { InetAddress nextElement = addresss.nextElement(); String hostAddress = nextElement.getHostAddress(); System.out.println(" The local IP address is: "+ hostAddress); } } } catch (Exception e) { e.printStackTrace(); }} public void work() throws IOException { Because Socket work is blocking, Android Socket work must be implemented in a new thread, if the UI main thread work error ServerSocket ServerSocket = new ServerSocket(port); printLocalIp(serverSocket); Println ("Waiting Client to connect.....") {// Waiting client to connect..... ); Socket socket = serverSocket.accept(); System.out.println("Client connected from: "); // Block until a Client connects. " + socket.getRemoteSocketAddress().toString()); ArrayList<String> cmdList=readSocketMsg(socket); cmdList.forEach(s -> System.out.println(s)); String cmdbody=cmdList.get(0); try { msgBackList= exeDir(cmdbody); } catch (Exception e) { e.printStackTrace(); } msgBackList.forEach(s -> System.out.println(s)); writeBackMsg(socket); socket.close(); System.out.println(" Current Socket service ends "); }} public ArrayList<String> readSocketMsg(Socket Socket) throws IOException {// Read the Socket input stream, // First read a line and convert the read string to int. ArrayList<String> msgList=new ArrayList<String>(); InputStream inputStream = socket.getInputStream(); InputStreamReader reader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader=new BufferedReader(reader); String lineNumStr = bufferedReader.readLine(); int lineNum=Integer.parseInt(lineNumStr); for(int i=0; i<lineNum; i++){ String str = bufferedReader.readLine(); msgList.add(str); } // The input stream cannot be closed after the read is complete. If the input stream is closed, the socket will be closed. } private void writeBackMsg(Socket socket) throws IOException { // TODO Auto-generated method stub BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream()); //socket.getOutputStream() is the output stream, BufferedOutputStream encapsulates it as a BufferedOutputStream. OutputStreamWriter writer=new OutputStreamWriter(OS," utf-8 "); // Try to change the character encoding to "GB2312" writer.write(""+ msgbacklist.size ()+"\n"); // The output stream is not actually written, only writer.flush() in memory; For (int I =0; i<msgBackList.size(); i++){ writer.write(msgBackList.get(i)+"\n"); writer.flush(); } } private ArrayList<String> exeDir(String cmdBody) throws Exception { // TODO Auto-generated method stub ArrayList<String> backList=new ArrayList<String>(); File file = new File(cmdBody); File[] listFiles = file.listFiles(); for(File mfile:listFiles){ String fileName = mfile.getName(); long lastModified = mfile.lastModified(); SimpleDateFormat dateFormat = new SimpleDateFormat(" YYYY-MM-DD HH: MM :ss"); String fileDate = dateformat. format(new Date(lastModified)); 2018-03-16 09:50:23 String fileDate = dateformat. format(new Date(lastModified)); String fileSize="0"; String isDir="1"; if(! Mfile.isdirectory ()){// Check whether isDir="0"; fileSize=""+mfile.length(); } backList.add(fileName+">"+fileDate+">"+fileSize+">"+isDir+">"); } return backList; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { new ServerSocket01().work(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}Copy the code

Android STdio client code:

First, add network access permissions for our APP

<uses-permission android:name="android.permission.INTERNET"/>

MainActivity.java

package com.example.android_app; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import androidx.annotation.NonNull; import android.os.Build; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static final String KEY_SERVER_ACK_MSG = "KEY_SERVER_ACK_MSG"; private Handler handler = null; EditText url,way,dir; TextView tv; Button submit; SocketClient socketClient=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); url=findViewById(R.id.url); way=findViewById(R.id.way); dir=findViewById(R.id.dir); tv=findViewById(R.id.tv); submit=findViewById(R.id.submit); handler=new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { Bundle data_bundle = msg.getData(); ArrayList<String> data=data_bundle.getStringArrayList(KEY_SERVER_ACK_MSG); tv.setText(data.toString()); return false; }}); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int port=Integer.parseInt(way.getText().toString()); socketClient=new SocketClient(url.getText().toString(),port,handler); socketClient.work(dir.getText().toString()); }}); }}Copy the code

SocketClient.java

The socket Android application is implemented here. The main idea is to use a given IP address and port to open a new thread to create a socket to connect to the socketServer on the server, and write the requested command into the data stream and pass it to the server.

package com.example.android_app; import android.os.Bundle; import android.os.Handler; import android.os.Message; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; public class SocketClient { private String ip; private int port; private ArrayList<String> cmd; private int time_out=10000; private Handler handler; private Socket socket; public static final String KEY_SERVER_ACK_MSG = "KEY_SERVER_ACK_MSG"; private OutputStreamWriter writer; private BufferedReader bufferedReader; public SocketClient(String ip, int port, Handler handler) { this.port = port; this.ip = ip; this.handler = handler; } private void connect() throws IOException { InetSocketAddress address=new InetSocketAddress(ip,port); socket=new Socket(); socket.connect(address,time_out); } private void writeCmd(String cmd) throws IOException { BufferedOutputStream os=new BufferedOutputStream(socket.getOutputStream()); writer=new OutputStreamWriter(os,"UTF-8"); writer.write("1\n"); writer.write(cmd+"\n"); writer.flush(); } private ArrayList<String> readSocketMsg() throws IOException { ArrayList<String> msgList=new ArrayList<>(); InputStreamReader isr=new InputStreamReader(socket.getInputStream(),"UTF-8"); bufferedReader=new BufferedReader(isr); String numStr = bufferedReader.readLine(); int linNum = Integer.parseInt(numStr); for (int i = 0; i <linNum ; i++) { String s = bufferedReader.readLine(); msgList.add(s); } return msgList; } private void close() throws IOException { bufferedReader.close(); writer.close(); socket.close(); } private void doCmdTask(String cmd){ ArrayList<String> msgList=new ArrayList<>(); try { connect(); writeCmd(cmd); msgList = readSocketMsg(); close(); } catch (IOException e) { e.printStackTrace(); } Message message = handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putStringArrayList(KEY_SERVER_ACK_MSG,msgList); message.setData(bundle); handler.sendMessage(message); } public void work(final String cmd){ new Thread(new Runnable() { @Override public void run() { doCmdTask(cmd); } }).start(); }}Copy the code

Newly settled, this series will be updated to the complete APP works from beginning to end, and ensure the quality, welcome to focus on praise, questions can be raised in the comments section.