客户端读取服务器端的文件目录,自主选择进行下载。(AS实现)
1.Manifest添加权限
与之前博文相同,不再赘述。详见:
Socket通信-CSDN博客文章浏览阅读272次,点赞4次,收藏10次。套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。socket通信只能在同一子网下,也就是说两个手机(Android设备)必须连接同一WIFI,不能说一个手机连着WIFI,一个手机用流量。分客户端与服务端,Socket以服务端的ip地址和定好的端口号进行组合得到套接字进行两端的相互连接,达到能够互相收发消息的目的。首先需要创建两个app工程,一个作为客户端,一个作为服务器端。https://blog.csdn.net/m0_65627943/article/details/135881909?spm=1001.2014.3001.5501
2.客户端
执行过程:
1. 打开客户端后,点击“连接”按钮,发送连接请求并发送读取服务器文件列表消息给服务器,然后服务器把文件列表返回,客户端再在界面上显示。之后客户端可进行下载操作。
2. 为了能方便服务器识别客户端消息的类型然后进行相应处理,简单规范化双方通信协议。通信格式如下:
关键代码块:
完整代码:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button refresh;
private Button commit;
private Button connect;
private TextView textProgress;
private TextView commitProgress;
private RecyclerView recyclerView;
Thread Thread1 = null;
private File currentUpploadFile;
private String downloadSavePath = "sdcard/Movies";
private Socket client_socket;
private PrintStream client_out;
private BufferedReader client_in;
private String ip = "192.168.236.147";
private int port = 5203;
private List<String> mData;
private FileListAdapter fileListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
initView();
//初始化数据
mData = new ArrayList<>();
//连接服务器
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread1 = new Thread(new Thread1());
Thread1.start();
}
});
//刷新文件列表
refresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO: 2024/2/2
}
});
// //设置Adapter和LayoutManager布局管理器
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
/**
* 初始化view
*/
private void initView() {
refresh = findViewById(R.id.refresh);
commit = findViewById(R.id.commit);
connect = findViewById(R.id.connect);
textProgress = findViewById(R.id.text_progress);
commitProgress = findViewById(R.id.commit_progress);
recyclerView = findViewById(R.id.recycler_view);
}
/**
* 连接服务器
*/
class Thread1 implements Runnable {
@Override
public void run() {
try {
client_socket = new Socket(ip, port);//建立连接
client_out = new PrintStream(client_socket.getOutputStream(), true);
client_in = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
//读取文件列表
client_out.println("@action=loadFileList");
Log.d(TAG, "run: Connected");
//开启线程监听服务器消息
new ClientThread().start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* item点击监听向服务器请求下载
*/
class downThread implements Runnable {
private List<String> data;
private int position;
downThread(List<String> data, int i) {
this.data = data;
this.position = i;
}
@Override
public void run() {
//向服务器请求下载
client_out.println("@action=Download[" + mData.get(position)