首页
社区
课程
招聘
[下载][推荐][原创]手机局域网文件分享
发表于: 2022-3-11 10:31 5059

[下载][推荐][原创]手机局域网文件分享

2022-3-11 10:31
5059

项目使用TCP进行文件传输,接收端做为服务端,发送端为客户端
更多惊喜:https://bbs.pediy.com/user-854079-1.htm
之前发过一个类型的,是双向服务,这次为单项,服务端不能直接向客户端请求

源码在附件中

思路如下
1,服务端开启服务,设置好端口(随机)
2,客户端扫描局域网中所有IP(设备名新协议已经不支持获取),选中要连接的IP,填入端口号,进行连接
3,客户端选择文件并请求上传文件,等待中
4,服务端确认要收文件
5,客户端开始上传文件
使用DataOutputStream进行数据的传输,其中writeUTF可以作为附加数据,可当作请求参数使用
代码均为测试,比较简陋,优化程度较大,有兴趣可在此基础上自由发挥

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
protected static final String TAG = "FileActivity";
private static int SERVER_PORT = 8990; // 服务端端口
private TextView tvMsg;
private Button btnClick;
private Button btnConnent;
private ListView lvList;
private NetTools netUtils;
private DevicesAdapter adapter;
private File sendFile;
private boolean isService;
protected boolean isConnent;//连接成功后为true
 
@Override
protected void onCreateView(Bundle arg0) {
    setContentView(R.layout.act_file_layout);
    setTitle("文件传输");
    netUtils = new NetTools();
    tvMsg = findView(R.id.tv_msg);
    lvList = findView(R.id.lv_list);
    tvProgress = findView(R.id.tv_progress);
    lvList.setVisibility(View.INVISIBLE);
    isService = getIntent().getBooleanExtra("server", true);
    btnClick = findView(R.id.btn_click);
    pb = findView(R.id.pb_file);
    pb.setMax(100);
    pb.setProgress(0);
    btnConnent = findView(R.id.btn_connent);
    btnConnent.setOnClickListener(scanDevice());
    isConnent = false;
    restInitialize();
    if(isService) {//服务端
        openSelect(1);
    }else{//客户端
        openSelect(2);
    }
    adapter = new DevicesAdapter();
    lvList.setAdapter(adapter);
    DataListener listener = new DataListener() {
        @Override
        public void onError(int index, String msg) {
            Message msg1 = new Message();
            msg1.obj = "error:"+msg;
            if(!isService && index >500) {
                msg1.what = 104;
 
            }
            handler.sendMessage(msg1);
        }
 
        @Override
        public void onPrepare(SocketSpec type) {
            Message msg = new Message();
            if(isService) {
                String ipAddress = NetWorkUtil.getIPAddress(FileActivity.this);
                msg.obj = "准备好了,IP:"+(ipAddress==null?"本机":ipAddress)+" 代码为:"+type.getProt();
            }else {
                msg.obj = "准备上传...";
                isConnent = true;
            }
            handler.sendMessage(msg);
 
        }
        @Override
        public String onReceive(String sb) {
            Message msg2 = new Message();
            msg2.obj = sb.toString();
            handler.sendMessage(msg2);
            return "我已收到信息";
        }
        @Override
        public void onRequestUploadFile(String file) {
            Message msg = new Message();
            if(isService) {
                msg.what = 102;
                msg.obj = "点击同意接收文件:"+file;
            }else {
                msg.obj = "文件开始上传"+file;
            }
            handler.sendMessage(msg);
        }
        @Override
        public void onClientConnentOk(String ip) {//连接服务端成功
            isConnent = true;
            Message msg = new Message();
            msg.what = 103;
            msg.obj = ip;
            handler.sendMessage(msg);
            super.onClientConnentOk(ip);
        }
        @Override
        public void onSaveFileing(File file, long pos, long size) {
            //pb
            int pro = (int) (pos*100/size);
            fileLengProgress = pro;
            pb.setProgress(pro);
            Message msg = new Message();
            msg.what = 105;
            if(isService) {
                msg.obj = "保存文件:"+file.getAbsolutePath()+" "+SizeUtils.fileSize(pos)+"/"+SizeUtils.fileSize(size);
            }else {
                msg.obj = "上传文件:"+file.getAbsolutePath()+" "+SizeUtils.fileSize(pos)+"/"+SizeUtils.fileSize(size);
            }
            handler.sendMessage(msg);
 
        }
        @Override
        public void onUploadFileSuccess(String file,boolean isSuccess) {
            Message msg = new Message();
            msg.what = 106;
            if(isService) {
                msg.obj = "接收文件:"+file+(isSuccess?"成功":"失败");
 
            }else {
                msg.obj = "发送文件:"+file+(isSuccess?"成功":"失败");
            }
            handler.sendMessage(msg);
        }
    };
    if(isService) {
        netUtils.setServerListener(listener);
    }else {
        netUtils.setClientListener(listener);
    }
 
 
}
 
@Override
protected void onResume() {
    super.onResume();
}
int fileLengProgress=0;
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        System.out.println("msg.what = "+msg.what);
        if(msg.what == 106) {//文件上传结束
            tvMsg.setText(msg.obj.toString());
            if(isService) {//服务端
                btnClick.setText("选择要接收的目录");
                btnClick.setOnClickListener(openFile(1));
                btnConnent.setText("开启接收");
                btnClick.setEnabled(true);
                btnConnent.setEnabled(false);
 
            }else{//客户端
                setTitle("文件发送");
                btnConnent.setText("重新搜索设备");
                btnClick.setText("再次发送的文件");
                btnClick.setOnClickListener(openFile(2));
                btnClick.setEnabled(true);
                btnConnent.setEnabled(false);
 
            }
        }
        else if(msg.what == 105) {
            tvProgress.setText(msg.obj.toString());
            if(isService) {
                btnClick.setEnabled(false);
 
            }else {
                btnClick.setEnabled(false);
                btnConnent.setEnabled(false);
            }
            tvProgress.setText(fileLengProgress+"%");
            tvMsg.setText(msg.obj.toString());
 
        }else if(msg.what == 104) {
            adapter.setReset();
            tvMsg.setText("连接错误");
        }
        else if(msg.what == 103) {
            lvList.setVisibility(View.INVISIBLE);
            if(isService) {
                tvMsg.setText("成功连接:"+msg.obj.toString());
                btnConnent.setEnabled(true);
            }
            if(isConnent && sendFile.isFile()) {
                btnClick.setText("开始发送");
                btnClick.setEnabled(true);
                btnClick.setOnClickListener(sendFile(sendFile));
                hideInputMethod();
            }
            btnConnent.setText("断开连接");
            btnConnent.setOnClickListener(getClose());
        }else if(msg.what == 102) {//服务端
            tvMsg.setText(msg.obj.toString());
            btnClick.setText("同意接收文件");
            btnConnent.setText("不同意接收");
            btnClick.setEnabled(true);
            btnConnent.setEnabled(true);
            btnConnent.setOnClickListener(getClose());
            btnClick.setOnClickListener(getOpenFile());//打开接收文件
        }else if(msg.what == 100) {//搜索中
            tvMsg.setText("尝试连接:"+msg.obj.toString());
        }else if(msg.what == 101){
            List<String> list = (List<String>) msg.obj;
            lvList.setVisibility(View.VISIBLE);
            adapter.setListData(list);
            adapter.notifyDataSetChanged();
            btnConnent.setText("重新搜索");
            btnConnent.setOnClickListener(scanDevice());
        }else {
            tvMsg.setText(msg.obj.toString());
        }
        super.handleMessage(msg);
    }
 
 
};
/**
 * 中断接收文件
 * @return
 */
private View.OnClickListener stopSaveFile(){
    return new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            netUtils.stopUploadFile();
            btnClick.setEnabled(true);
            restInitialize();
        }
    };
}
/**
 * 开始发送文件
 * @param file
 * @return
 */
private View.OnClickListener sendFile(File file){
    return new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            tvMsg.setText("文件准备中... "+sendFile.getName());
            netUtils.uploadFile(sendFile);
        }
    };
}
 
/**
 * 关闭连接
 * @return
 */
private View.OnClickListener getClose(){
    return new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            netUtils.stopUploadFile();
            netUtils.closeClent();
            netUtils.colseServer();
            restInitialize();
 
 
        }
    };
}
/**
 * 打开接收文件
 * @return
 */
private View.OnClickListener getOpenFile() {
    // TODO Auto-generated method stub
    return new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            netUtils.setSaveFilePath(sendFile);
            netUtils.setEnableReceiveFile(true);
            btnClick.setEnabled(false);
            btnClick.setText("重新选择保存目录");
            btnConnent.setText("断开连接");
            btnConnent.setOnClickListener(stopSaveFile());
        }
    };
}
private int port;
private ProgressBar pb;
private TextView tvProgress;
 
/**
 *
 * @param i 1选择目录,2选择文件
 * @return
 */
private View.OnClickListener openFile(final int i){
    return new View.OnClickListener() {
 
        @Override
        public void onClick(View v) {
            v.setEnabled(false);
            openSelect(i);
        }
    };
}
/**
 *
 * @param i 连接
 * @return
 */
private View.OnClickListener scanDevice(){
    return new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ScanDeviceTool tool = new ScanDeviceTool();
            tool.setScanDevicesListener(new ScanDevicesListener() {
 
                @Override
                public void onResult(String ip, boolean count) {
                    try {
                        Message message = new Message();
                        message.what = 100;
                        message.obj = ip+" "+(count ? "-------------- 成功" : "失败");
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
 
                }
 
                @Override
                public void onSuccess(List<String> mIpList) {
                    List<String> iPs = getIPs();
                    Message message = new Message();
                    message.what = 101;
                    message.obj = mIpList;
                    handler.sendMessage(message);
 
                }
            });
            tool.start();
        }
    };
}
/**
 *
 * @param type 1选择目录,2选择文件
 */
private void openSelect(int type) {
    Intent intent = new Intent(this, SelectFileActivity.class);
    intent.putExtra("type", type);
    startActivityForResult(intent, 100);
}
/**
 * 打开服务
 */
private void openServer() {
    int ran = new Random().nextInt(9000)+1000;
    this.port = ran;
    netUtils.openService(ran);
    btnClick.setText("重新选择目录");
}
@Override
protected void onActivityResult(int arg0, int arg1, Intent intent) {
    if(arg0==100 && intent!=null) {
        File file = (File) intent.getSerializableExtra("file");
        this.sendFile = file;
        if(isService) {//接收端
            tvMsg.setText("已选择接收目录:"+file.getAbsolutePath());
            openServer();
        }else {
            tvMsg.setText("已选择发送文件:"+file.getAbsolutePath());
            btnClick.setText("开始发送");
            btnClick.setEnabled(isConnent);
            btnClick.setOnClickListener(sendFile(file));
        }
 
    }
    super.onActivityResult(arg0, arg1, intent);
}
class DevicesAdapter extends BaseAdapter{
    int select = -1;
    @Override
    public long getItemId(int arg0) {
 
        return 0;
    }
 
    public void setReset() {
        select = -1;
        notifyDataSetChanged();
 
    }
 
    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        View inflate = View.inflate(getBaseContext(), R.layout.port_list_layout, null);
        String data = getData(arg0);
        TextView tvIP = (TextView) inflate.findViewById(R.id.tv_port);
        tvIP.setText(data);
        Button btnConnent = (Button) inflate.findViewById(R.id.btn_connent);
        final TextView etPort = (TextView) inflate.findViewById(R.id.et_port);
        btnConnent.setTag(arg0);
        if(select<0 || select ==arg0) {
            btnConnent.setEnabled(true);
            etPort.setEnabled(true);
        }else {
            etPort.setEnabled(false);
            btnConnent.setEnabled(false);
        }
        if(select==arg0) {
            btnConnent.setText("断开");
        }else {
            btnConnent.setText("连接");
        }
        btnConnent.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                Button btn = (Button) v;
                int pos = Integer.parseInt(v.getTag().toString());
                String path = getData(pos);
                if(select==pos) {
                    select = -1;
                }else {
                    select = pos;
 
                }
                String prot = etPort.getText().toString();
                if(TextUtils.isEmpty(prot)) {
                    T.showShort(getBaseContext(), "代码未填写");
                    select = -1;
                    return;
                }
                if(!prot.trim().matches("\\d{4}")) {
                    T.showShort(getBaseContext(), "代码有误");
                    select = -1;
                    return;
                }
                notifyDataSetChanged();
                connent(path, Integer.parseInt(prot));
 
            }
        });
        return inflate;
    }
 
}
private void restInitialize () {
    if(isService) {//服务端
        setTitle("文件接收");
        btnClick.setText("选择要接收的目录");
        btnClick.setOnClickListener(openFile(1));
        btnConnent.setText("开启接收");
        btnConnent.setEnabled(false);
    }else{//客户端
        setTitle("文件发送");
        btnConnent.setText("搜索设备");
        btnClick.setText("选择要发送的文件");
        btnConnent.setOnClickListener(scanDevice());
        btnClick.setOnClickListener(openFile(2));
    }
}
/**
 * 开始连接到服务
 * @param ip
 * @param prot
 */
private void connent(String ip,int prot) {
    isConnent = false;
    netUtils.openClient(ip, prot);
    netUtils.connentClient();
    tvMsg.setText("创建连接中:"+ip+"/"+prot);
}
 
@Override
protected void onDestroy() {
    netUtils.colseServer();
    netUtils.closeClent();
    super.onDestroy();
}
public static List<String> getIPs() {
    List<String> list = new ArrayList<String>();
    boolean flag = false;
    int count = 0;
    Runtime r = Runtime.getRuntime();
    Process p;
    try {
        p = r.exec("arp -a");
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
        String inline;
        while ((inline = br.readLine()) != null) {
            System.out.println(inline);
            if(inline.length()<=0) {
                continue;
            }
            if(!inline.trim().matches("\\d+.*")) {
                continue;
            }
            list.add(inline.trim().replaceAll("^((\\d+\\.){3}\\d+).*$", "$1"));
        }
        br.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(list);
    return list;
}
 
 
 
public void onBtnClose(View view) {
 
 
}

[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!

最后于 2022-3-11 14:37 被富到流油^-^编辑 ,原因: 补充
上传的附件:
收藏
免费 1
支持
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回
//