安卓socket实例(一)实现简单的文件列表访问

安卓socket实例(一)实现简单的文件列表访问

Android小彩虹2021-08-19 12:50:00220A+A-

(一)使用socket技术使得安卓端可以访问电脑目录,并将其结果返回至安卓端。

image.png

思路讲解:

image.png 安卓端负责通过基础设计在用户触发指定事件时将指定命令写入输入流传入服务端。

idea的服务端开启后,负责实时解析处理安卓端传入的数据流命令,并将运行结果返回。

idea服务端代码:

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;// 自定义一个端口,端口号尽可能挑选一些不被其他服务占用的端口,祥见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) {// 枚举打印服务端的IP
        try {
            System.out.println("服务端命令端口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("本机IP地址为:" + hostAddress);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void work() throws IOException {
        // 注意:由于Socket的工作是阻塞式,Android端Socket的工作必须在新的线程中实现,若在UI主线程中工作会报错

        ServerSocket serverSocket = new ServerSocket(port);
        printLocalIp(serverSocket);
        while (true) {// 无限循环,使之能结束当前socket服务后,准备下一次socket服务

            System.out.println("Waiting client to connect.....");
            Socket socket = serverSocket.accept();// 阻塞式,直到有客户端连接进来,才会继续往下执行,否则一直停留在此代码
            System.out.println("Client connected from: "
                    + 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("当前Socket服务结束");

        }
    }
    public ArrayList<String> readSocketMsg(Socket socket) throws IOException {
        // 读socket的输入流,传入的socket参数是已经连接成功未处于关闭的socket
        //首先读取一行,并将读取的字符串内容转换为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);
        }
        //读取结束后,输入流不能关闭,此时关闭,会将socket关闭,从而导致后续对socket写操作无法实现
        return msgList;
    }
    private void writeBackMsg(Socket socket) throws IOException {
        // TODO Auto-generated method stub
        BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());//socket.getOutputStream()是输出流,BufferedOutputStream则将其封装为带缓冲的输出流
        OutputStreamWriter writer=new OutputStreamWriter(os,"UTF-8");//尝试将字符编码改成"GB2312"
        writer.write(""+msgBackList.size()+"\n");//未真正写入的输出流,仅仅在内存中
        writer.flush();//写入输出流,真正将数据传输出去

        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");//给时间格式,例如:2018-03-16 09:50:23
            String fileDate = dateFormat.format(new Date(lastModified));//取得文件最后修改时间,并按格式转为字符串
            String fileSize="0";
            String isDir="1";
            if(!mfile.isDirectory()){//判断是否为目录
                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();
        }

    }

}


android stdio客户端代码:

首先为我们的APP添加访问网络的权限

image.png

<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());
            }
        });

    }

}


SocketClient.java

socket安卓端的应用在这里实现,主要思路为通过给定的ip地址与端口,新开启一个线程创建socket去连接服务端的socketserver,并将所请求的命令写入数据流,传入服务端。

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();
    }
}

新入驻,此系列将从头到尾更新至完整APP作品,并且保证质量,欢迎关注点赞,有疑问可在评论区提出。

点击这里复制本文地址 以上内容由权冠洲的博客整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

支持Ctrl+Enter提交

联系我们| 本站介绍| 留言建议 | 交换友链 | 域名展示
本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除

权冠洲的博客 © All Rights Reserved.  Copyright quanguanzhou.top All Rights Reserved
苏公网安备 32030302000848号   苏ICP备20033101号-1
本网站由 提供CDN/云存储服务

联系我们