├── .gitignore ├── MySocket.iml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── accvmedia │ │ └── mysocket │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── accvmedia │ │ │ └── mysocket │ │ │ ├── ClientActivity.java │ │ │ ├── Constant.java │ │ │ ├── MainActivity.java │ │ │ ├── ServerActivity.java │ │ │ ├── ServerAdapter.java │ │ │ ├── bean │ │ │ ├── BroadcastBean.java │ │ │ ├── SocketBean.java │ │ │ └── TaskBean.java │ │ │ ├── jobqueue │ │ │ ├── SocketJob.java │ │ │ └── SocketJobManager.java │ │ │ ├── receiver │ │ │ └── WifiChangedReceiver.java │ │ │ ├── socket │ │ │ ├── ClientThread.java │ │ │ ├── MulticastThread.java │ │ │ ├── ServerRunnable.java │ │ │ └── SocketManager.java │ │ │ └── util │ │ │ ├── DebugLogger.java │ │ │ ├── FileUtils.java │ │ │ └── WifiUtils.java │ └── res │ │ ├── layout │ │ ├── act_new_client.xml │ │ ├── activity_main.xml │ │ ├── activity_server.xml │ │ ├── client_item_list.xml │ │ └── item_list.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── accvmedia │ └── mysocket │ └── ExampleUnitTest.java ├── art └── socket.gif ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── local.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | *.iml 37 | .idea/workspace.xml 38 | 39 | # Keystore files 40 | *.jks 41 | -------------------------------------------------------------------------------- /MySocket.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # android_socket 2 | ### 文件传输流程: 3 | 1. 通过局域网广播的方式通知其他客户端服务器ip地址和要发送的文件列表 4 | 2. 客户端收到广播后,主动连接服务器传入需要的文件名 5 | 3. 通信协议为子节流的前4个字节表示数据长度,后面紧跟要发的内容,发送时都是先发内容长度再发具体内容,接收端也是一样 6 | ### 项目特性: 7 | 1. 支持多个文件传输,用了任务调度框架[priority-jobqueue](https://github.com/yigit/android-priority-jobqueue "priority-jobqueue") 8 | 2. 对socket进行了一些封装,提供一系列回调,连接成功,文件进度,出现异常等 9 | 3. 传输过程中socket超时,支持自动重连 10 | 4. 局域网传输文件,支持断点续传 11 | 5. 交互协议通过json格式进行通信,通用型更强 12 | 6. 支持一对多传输 13 | 14 | #### *因为模拟器不能发局域网广播,只能手动输入ip和需要的文件名* 15 | ![df](art/socket.gif) -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.3" 6 | 7 | defaultConfig { 8 | applicationId "com.accvmedia.mysocket" 9 | minSdkVersion 15 10 | targetSdkVersion 23 11 | versionCode 1 12 | versionName "1.4.4" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | testCompile 'junit:junit:4.12' 25 | compile 'com.android.support:appcompat-v7:23.0.1' 26 | compile 'com.android.support:recyclerview-v7:23.0.1' 27 | compile 'com.nononsenseapps:filepicker:2.5.2' 28 | compile 'com.google.code.gson:gson:2.2.4' 29 | compile 'com.birbit:android-priority-jobqueue:2.0.1' 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/accvmedia/mysocket/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest 10 | extends ApplicationTestCase 11 | { 12 | public ApplicationTest() { 13 | super(Application.class); 14 | } 15 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/ClientActivity.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.util.Log; 6 | import android.view.View; 7 | import android.view.ViewGroup; 8 | import android.widget.AdapterView; 9 | import android.widget.BaseAdapter; 10 | import android.widget.Button; 11 | import android.widget.EditText; 12 | import android.widget.ListView; 13 | import android.widget.ProgressBar; 14 | import android.widget.TextView; 15 | import android.widget.Toast; 16 | 17 | import com.accvmedia.mysocket.bean.BroadcastBean; 18 | import com.accvmedia.mysocket.jobqueue.SocketJob; 19 | import com.accvmedia.mysocket.socket.SocketManager; 20 | import com.accvmedia.mysocket.util.FileUtils; 21 | import com.accvmedia.mysocket.util.WifiUtils; 22 | 23 | import java.io.BufferedReader; 24 | import java.io.File; 25 | import java.io.FileInputStream; 26 | import java.io.IOException; 27 | import java.io.PrintWriter; 28 | import java.net.ConnectException; 29 | import java.net.InetAddress; 30 | import java.net.Socket; 31 | import java.net.SocketTimeoutException; 32 | import java.text.SimpleDateFormat; 33 | import java.util.ArrayList; 34 | import java.util.List; 35 | import java.util.Properties; 36 | 37 | /** 38 | * Created by dempseyZheng on 2017/3/14 39 | */ 40 | public class ClientActivity extends AppCompatActivity 41 | implements 42 | View.OnClickListener, 43 | SocketManager.OnClientListener { 44 | 45 | private static final String TAG = "ClientActivity"; 46 | private TextView tv_msg = null; 47 | private Button btn_send = null; 48 | // private Button btn_login = null; 49 | private Socket socket = null; 50 | private BufferedReader in = null; 51 | private PrintWriter out = null; 52 | private String content = ""; 53 | private EditText EditText01; 54 | private Button Button02; 55 | private EditText et_host_ip; 56 | private Button btn_connect; 57 | private ProgressBar progressBar; 58 | private String path = ""; 59 | private EditText edt_error_msg; 60 | private String fileName; 61 | private boolean isRunning = false; 62 | private String mPath; 63 | private long mFileLen; 64 | private InetAddress mReceiveAddress; 65 | private ListView act_client_lv; 66 | List mFileList = new ArrayList<>(); 67 | private EditText et_file_name; 68 | private ListView act_client_list_view; 69 | 70 | @Override 71 | protected void onCreate(Bundle savedInstanceState) { 72 | super.onCreate(savedInstanceState); 73 | setContentView(R.layout.act_new_client); 74 | initView(); 75 | getSupportActionBar().setTitle( 76 | "\t\t" + WifiUtils.getInstance().getParsedIp()); 77 | SocketManager.getInstance().setOnClientListener(this); 78 | // receiveBroadcast(); 79 | act_client_lv.setAdapter(mBaseAdapter); 80 | act_client_lv 81 | .setOnItemClickListener(new AdapterView.OnItemClickListener() { 82 | @Override 83 | public void onItemClick(AdapterView parent, View view, 84 | int position, long id) { 85 | 86 | BroadcastBean.FilesBean filesBean = mFileList 87 | .get(position); 88 | mFileLen = filesBean.length; 89 | mPath = Constant.RECEIVE_FILE_DIR + "/" 90 | + filesBean.name; 91 | int offset = getOffset(new File(mPath + ".log")); 92 | SocketManager.getInstance().newClient(mHostIp, 93 | Constant.PORT, mPath, mFileLen, offset, 94 | new SocketJob.FileCallBack() { 95 | @Override 96 | public void onProgress(int progress) { 97 | progressBar.setProgress(progress); 98 | } 99 | 100 | @Override 101 | public void onStartReceive( 102 | final String filename, 103 | final int file_len) { 104 | 105 | progressBar.setMax(file_len); 106 | } 107 | }); 108 | } 109 | }); 110 | } 111 | 112 | private BaseAdapter mBaseAdapter = new BaseAdapter() { 113 | class ViewHolder { 114 | public View rootView; 115 | public TextView client_tv_name; 116 | public TextView client_tv_len; 117 | 118 | public ViewHolder(View rootView) { 119 | this.rootView = rootView; 120 | this.client_tv_name = (TextView) rootView 121 | .findViewById(R.id.client_tv_name); 122 | this.client_tv_len = (TextView) rootView 123 | .findViewById(R.id.client_tv_len); 124 | } 125 | 126 | } 127 | 128 | @Override 129 | public int getCount() { 130 | if (mFileList != null) { 131 | return mFileList.size(); 132 | } 133 | return 0; 134 | } 135 | 136 | @Override 137 | public Object getItem(int position) { 138 | return mFileList.get(position); 139 | } 140 | 141 | @Override 142 | public long getItemId(int position) { 143 | return position; 144 | } 145 | 146 | @Override 147 | public View getView(int position, View convertView, ViewGroup parent) { 148 | ViewHolder holder = null; 149 | if (convertView == null) { 150 | convertView = View.inflate(ClientActivity.this, 151 | R.layout.client_item_list, null); 152 | holder = new ViewHolder(convertView); 153 | convertView.setTag(holder); 154 | } else { 155 | holder = (ViewHolder) convertView.getTag(); 156 | } 157 | // 设置数据 158 | BroadcastBean.FilesBean filesBean = mFileList.get(position); 159 | holder.client_tv_name.setText(filesBean.name); 160 | holder.client_tv_len.setText(filesBean.length + "字节"); 161 | return convertView; 162 | } 163 | }; 164 | private String mHostIp; 165 | 166 | private int getOffset(File file) { 167 | int position = 0; 168 | if (file.exists()) { 169 | Properties properties = new Properties(); 170 | try { 171 | properties.load(new FileInputStream(file)); 172 | } catch (IOException e) { 173 | e.printStackTrace(); 174 | } 175 | position = Integer.valueOf(properties.getProperty("length"));// 读取断点的位置 176 | } 177 | return position; 178 | } 179 | 180 | private boolean isFileReceived(String path, long fileLen) { 181 | File file = new File(path); 182 | 183 | if (file.exists() && file.length() == fileLen) { 184 | return true; 185 | } 186 | return false; 187 | } 188 | 189 | private void initView() { 190 | et_host_ip = (EditText) findViewById(R.id.et_host_ip); 191 | btn_connect = (Button) findViewById(R.id.btn_connect); 192 | 193 | btn_connect.setOnClickListener(this); 194 | progressBar = (ProgressBar) findViewById(R.id.progressBar); 195 | edt_error_msg = (EditText) findViewById(R.id.edt_error_msg); 196 | edt_error_msg.setOnClickListener(this); 197 | act_client_lv = (ListView) findViewById(R.id.act_client_list_view); 198 | et_file_name = (EditText) findViewById(R.id.et_file_name); 199 | act_client_list_view = (ListView) findViewById(R.id.act_client_list_view); 200 | } 201 | 202 | @Override 203 | public void onClick(View v) { 204 | switch (v.getId()) { 205 | 206 | case R.id.btn_connect : 207 | connect(et_host_ip.getText().toString().trim(), 208 | Constant.RECEIVE_FILE_DIR + "/" 209 | + et_file_name.getText().toString().trim(), 0); 210 | break; 211 | } 212 | } 213 | 214 | @Override 215 | protected void onDestroy() { 216 | super.onDestroy(); 217 | 218 | } 219 | 220 | private void connect(String hostIp, String path, long len) { 221 | // 判断文件是否已经接收完成过 222 | 223 | Constant.HOST_IP = hostIp; 224 | 225 | SocketManager.getInstance().newClient(hostIp, 9999, path, len, 226 | getOffset(new File(mPath + ".log")), 227 | new SocketJob.FileCallBack() { 228 | 229 | @Override 230 | public void onProgress(int progress) { 231 | progressBar.setProgress(progress); 232 | } 233 | 234 | @Override 235 | public void onStartReceive(final String filename, 236 | final int file_len) { 237 | 238 | progressBar.setMax(file_len); 239 | } 240 | 241 | }); 242 | } 243 | 244 | @Override 245 | public void onConnected() { 246 | String msg = "连接成功"; 247 | // 连接成功 248 | Toast.makeText(ClientActivity.this, msg, Toast.LENGTH_SHORT).show(); 249 | String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 250 | .format(System.currentTimeMillis()); 251 | edt_error_msg.append("\n" + format + "-->" + msg); 252 | } 253 | 254 | @Override 255 | public void onReceiveFinished(String savepath) { 256 | Toast.makeText(ClientActivity.this, "文件接收完成", Toast.LENGTH_SHORT) 257 | .show(); 258 | String format = new SimpleDateFormat("yyyy-MM-dd H:m:s").format(System 259 | .currentTimeMillis()); 260 | edt_error_msg.append("\n" + format + "-->" + "文件接收完成"); 261 | // int index = savepath.lastIndexOf("."); 262 | // if (index == -1) { 263 | // return; 264 | // } 265 | // String substring = savepath.substring(index); 266 | // 267 | // if (substring.equals(".apk")) { 268 | // Intent intent = new Intent(Intent.ACTION_VIEW); 269 | // intent.setDataAndType(Uri.fromFile(new File(savepath)), 270 | // "application/vnd.android.package-archive"); 271 | // startActivity(intent); 272 | // } 273 | } 274 | 275 | @Override 276 | public void onError(Exception ex) { 277 | if (ex instanceof ConnectException) { 278 | Toast.makeText(ClientActivity.this, "连接异常", Toast.LENGTH_SHORT) 279 | .show(); 280 | 281 | } else if (ex instanceof SocketTimeoutException) { 282 | edt_error_msg.append("\n 连接超时,重连服务器..."); 283 | // connect(mHostIp, mPath, mFileLen); 284 | 285 | } else { 286 | Toast.makeText(ClientActivity.this, "出现异常", Toast.LENGTH_SHORT) 287 | .show(); 288 | 289 | } 290 | String format = new SimpleDateFormat("yyyy-MM-dd H:m:s").format(System 291 | .currentTimeMillis()); 292 | edt_error_msg.append("\n" + format + "-->" 293 | + Log.getStackTraceString(ex)); 294 | } 295 | 296 | @Override 297 | public void onMessage(String msg) { 298 | String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 299 | .format(System.currentTimeMillis()); 300 | edt_error_msg.append("\n" + format + "-->" + msg); 301 | } 302 | 303 | @Override 304 | public void onBroadcastMsg(BroadcastBean broadcastMsg) { 305 | switch (broadcastMsg.type) { 306 | case BroadcastBean.TYPE_CLEAR : 307 | boolean b = FileUtils 308 | .deleteFilesInDir(Constant.RECEIVE_FILE_DIR); 309 | edt_error_msg.append("\n" + "清空文件夹: " 310 | + Constant.RECEIVE_FILE_DIR + ",结果: " + b); 311 | break; 312 | case BroadcastBean.TYPE_FILE : 313 | mFileList.clear(); 314 | String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 315 | .format(System.currentTimeMillis()); 316 | edt_error_msg.append("\n" + format + "-->" + "接收到服务器ip地址: " 317 | + broadcastMsg.hostIp); 318 | for (int i = 0; i < broadcastMsg.files.size(); i++) { 319 | edt_error_msg.append("\n" + "接收的文件名: " 320 | + broadcastMsg.files.get(i).name + "," + "文件大小:" 321 | + broadcastMsg.files.get(i).length + "字节"); 322 | } 323 | mFileList = broadcastMsg.files; 324 | mBaseAdapter.notifyDataSetChanged(); 325 | mHostIp = broadcastMsg.hostIp; 326 | 327 | for (int i = 0; i < mFileList.size(); i++) { 328 | 329 | BroadcastBean.FilesBean filesBean = mFileList.get(i); 330 | long fileLen = filesBean.length; 331 | String path = Constant.RECEIVE_FILE_DIR + "/" 332 | + filesBean.name; 333 | int offset = getOffset(new File(path + ".log")); 334 | 335 | SocketManager.getInstance().newClient(mHostIp, 336 | Constant.PORT, path, fileLen, offset, 337 | new SocketJob.FileCallBack() { 338 | 339 | @Override 340 | public void onProgress(int progress) { 341 | progressBar.setProgress(progress); 342 | } 343 | 344 | @Override 345 | public void onStartReceive( 346 | final String filename, 347 | final int file_len) { 348 | 349 | progressBar.setMax(file_len); 350 | } 351 | 352 | }); 353 | } 354 | 355 | // mFileLen = broadcastMsg.files.get(0).length; 356 | // mPath = Constant.RECEIVE_FILE_DIR + "/" 357 | // + broadcastMsg.files.get(0).name; 358 | // int offset = getOffset(new File(mPath + ".log")); 359 | // SocketManager.getInstance() 360 | // .newClient(mHostIp, Constant.PORT, 361 | // mPath, mFileLen, offset, 362 | // new ClientThread.FileCallBack() { 363 | // @Override 364 | // public void onProgress(int progress) { 365 | // progressBar.setProgress(progress); 366 | // } 367 | // 368 | // @Override 369 | // public void onStartReceive(final String filename, 370 | // final int file_len) 371 | // { 372 | // 373 | // progressBar.setMax(file_len); 374 | // } 375 | // }); 376 | 377 | break; 378 | default : 379 | 380 | break; 381 | } 382 | 383 | // if (broadcastMsg.contains("clear")) { 384 | // boolean b = FileUtils.deleteFilesInDir(Constant.RECEIVE_FILE_DIR); 385 | // edt_error_msg.append("\n" + "清空文件夹: " + Constant.RECEIVE_FILE_DIR 386 | // + ",结果: " + b); 387 | // } else { 388 | // String[] split = broadcastMsg.split("=="); 389 | // if (split.length == 3) { 390 | // String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 391 | // .format(System.currentTimeMillis()); 392 | // edt_error_msg.append("\n" + format + "-->" + "接收到服务器ip地址: " 393 | // + split[0] + ",接收的文件名: " + split[1] + "," + "文件大小:" 394 | // + split[2] + "字节"); 395 | // mHostIp = split[0]; 396 | // mFileLen = Long.parseLong(split[2]); 397 | // mPath = Constant.RECEIVE_FILE_DIR + "/" + split[1]; 398 | 399 | // } 400 | // } 401 | } 402 | 403 | } 404 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/Constant.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket; 2 | 3 | import android.os.Environment; 4 | 5 | /** 6 | * Created by dempseyZheng on 2017/3/17 7 | */ 8 | public class Constant { 9 | public static final String RECEIVE_FILE_DIR = Environment.getExternalStorageDirectory() 10 | .getAbsolutePath()+"/distribute"; 11 | public static final long RECEIVE_FILE_LENGTH = 0; 12 | public static final String SEND_DIR = Environment.getExternalStorageDirectory() 13 | .getAbsolutePath() + "/send"; 14 | public static final String GROUP_ID = "SOCKET_GROUP"; 15 | public static final int PRIORITY = 999; 16 | public static String RECEIVE_FILE_PATH =""; 17 | public static String HOST_IP ="192.168.1.173"; 18 | public static int PORT =10086; 19 | public static String multicastHost ="224.0.0.1"; 20 | public static int multicastPort =10010; 21 | public static boolean isReceiving =false; 22 | public static boolean isServer =false; 23 | public static int SoTimeout=5*1000;//socket连接超时时间5秒 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.view.View; 7 | import android.widget.Button; 8 | import android.widget.TextView; 9 | 10 | import com.accvmedia.mysocket.jobqueue.SocketJobManager; 11 | import com.accvmedia.mysocket.socket.SocketManager; 12 | import com.accvmedia.mysocket.util.WifiUtils; 13 | 14 | public class MainActivity extends AppCompatActivity 15 | implements 16 | View.OnClickListener { 17 | 18 | private Button btn_server; 19 | private Button btn_client; 20 | private TextView tv_ip; 21 | private TextView tv_version; 22 | 23 | @Override 24 | protected void onCreate(Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | setContentView(R.layout.activity_main); 27 | WifiUtils.getInstance().init(this); 28 | SocketJobManager.getInstance().init(this); 29 | 30 | getSupportActionBar().setTitle( 31 | "\t\t" +"路由器mac地址:"+WifiUtils.getInstance().getBSSID()); 32 | initView(); 33 | SocketManager.getInstance().init(); 34 | tv_version.setText("版本号: "+BuildConfig.VERSION_NAME); 35 | 36 | 37 | 38 | } 39 | 40 | private void initView() { 41 | btn_server = (Button) findViewById(R.id.btn_server); 42 | btn_client = (Button) findViewById(R.id.btn_client); 43 | 44 | btn_server.setOnClickListener(this); 45 | btn_client.setOnClickListener(this); 46 | tv_ip = (TextView) findViewById(R.id.tv_ip); 47 | tv_ip.setOnClickListener(this); 48 | tv_ip.setText(WifiUtils.getInstance().getParsedIp()); 49 | tv_version = (TextView) findViewById(R.id.tv_version); 50 | } 51 | 52 | @Override 53 | public void onClick(View v) { 54 | switch (v.getId()) { 55 | case R.id.btn_server : 56 | startActivity(new Intent(MainActivity.this, 57 | ServerActivity.class)); 58 | break; 59 | case R.id.btn_client : 60 | startActivity(new Intent(MainActivity.this, 61 | ClientActivity.class)); 62 | 63 | break; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/ServerActivity.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Activity; 5 | import android.content.ClipData; 6 | import android.content.Intent; 7 | import android.net.Uri; 8 | import android.os.Build; 9 | import android.os.Bundle; 10 | import android.os.Environment; 11 | import android.os.Handler; 12 | import android.os.Message; 13 | import android.support.v7.app.AppCompatActivity; 14 | import android.support.v7.widget.RecyclerView; 15 | import android.util.Log; 16 | import android.view.LayoutInflater; 17 | import android.view.View; 18 | import android.view.ViewGroup; 19 | import android.widget.BaseAdapter; 20 | import android.widget.Button; 21 | import android.widget.EditText; 22 | import android.widget.ListView; 23 | import android.widget.ProgressBar; 24 | import android.widget.TextView; 25 | import android.widget.Toast; 26 | 27 | import com.accvmedia.mysocket.bean.BroadcastBean; 28 | import com.accvmedia.mysocket.bean.TaskBean; 29 | import com.accvmedia.mysocket.socket.MulticastThread; 30 | import com.accvmedia.mysocket.socket.ServerRunnable; 31 | import com.accvmedia.mysocket.socket.SocketManager; 32 | import com.accvmedia.mysocket.util.DebugLogger; 33 | import com.accvmedia.mysocket.util.WifiUtils; 34 | import com.nononsenseapps.filepicker.FilePickerActivity; 35 | 36 | import java.io.File; 37 | import java.net.ConnectException; 38 | import java.net.ServerSocket; 39 | import java.net.Socket; 40 | import java.text.SimpleDateFormat; 41 | import java.util.ArrayList; 42 | import java.util.HashMap; 43 | import java.util.List; 44 | import java.util.concurrent.ExecutorService; 45 | 46 | public class ServerActivity extends AppCompatActivity 47 | implements 48 | ServerRunnable.ProgressCallBack, 49 | View.OnClickListener, 50 | SocketManager.OnServerListener { 51 | 52 | private static final int PORT = 10086; 53 | private static final int FILE_CODE = 1010; 54 | private ServerSocket server; 55 | private ExecutorService mExecutorService; 56 | private ArrayList mList = new ArrayList<>(); 57 | public boolean isRunnning = true; 58 | private EditText et_client_msg; 59 | private ArrayList mDataList = new ArrayList<>(); 60 | private ArrayList mHolderList = new ArrayList<>(); 61 | 62 | private Handler mHandler = new Handler() { 63 | @Override 64 | public void handleMessage(Message msg) { 65 | super.handleMessage(msg); 66 | String format = ""; 67 | switch (msg.what) { 68 | case 0 : 69 | format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 70 | .format(System.currentTimeMillis()); 71 | et_client_msg.append("\n" + format + "-->" + msg.obj); 72 | break; 73 | case 1 : 74 | // mHomeAdapter.notifyDataSetChanged(); 75 | // mRecyclerView.smoothScrollToPosition(mDataList.size()-1); 76 | break; 77 | 78 | case 2 : 79 | Exception ex = (Exception) msg.obj; 80 | if (ex instanceof ConnectException) { 81 | Toast.makeText(ServerActivity.this, "连接异常", 82 | Toast.LENGTH_SHORT).show(); 83 | } 84 | 85 | else { 86 | Toast.makeText(ServerActivity.this, "出现异常", 87 | Toast.LENGTH_SHORT).show(); 88 | 89 | } 90 | String format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 91 | .format(System.currentTimeMillis()); 92 | et_error_msg.append("\n" + format1 + "-->" 93 | + Log.getStackTraceString(ex)); 94 | break; 95 | case 3 : 96 | System.out.print("server start ..."); 97 | 98 | format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 99 | .format(System.currentTimeMillis()); 100 | et_client_msg.append("\n" + format + "-->" 101 | + (String) msg.obj); 102 | break; 103 | case 4 : 104 | DebugLogger.e("开始发送"); 105 | TaskBean taskBean = (TaskBean) msg.obj; 106 | mDataList.add(taskBean); 107 | // Message message = Message.obtain(); 108 | // message.what = 1; 109 | // mHandler.sendMessage(message); 110 | DebugLogger.e("更新列表"); 111 | // mHomeAdapter.notifyDataSetChanged(); 112 | // mRecyclerView.smoothScrollToPosition(mDataList.size()-1); 113 | mAdapter.notifyDataSetChanged(); 114 | list_view.smoothScrollToPosition(mDataList.size() - 1); 115 | break; 116 | case 5 : 117 | // TaskBean progress= (TaskBean) msg.obj; 118 | // DebugLogger.d(progress.ip + ": " + progress.progress); 119 | // View view = null; 120 | // for (int i = 0; i < viewList.size(); i++) { 121 | // if (viewList.get(i).getTag(progress.hashCode()) != null) 122 | // { 123 | // view = viewList.get(i); 124 | // break; 125 | // } 126 | // } 127 | // if (view != null) { 128 | // ServerAdapter.ViewHolder viewHolder = 129 | // (ServerAdapter.ViewHolder) view 130 | // .getTag(); 131 | // viewHolder.item_pb.setProgress(progress.progress); 132 | // } 133 | TaskBean progress = (TaskBean) msg.obj; 134 | // for (int i = 0; i < mHolderList.size(); i++) { 135 | // HomeAdapter.MyViewHolder myViewHolder = 136 | // mHolderList.get(i); 137 | // 138 | // if 139 | // (myViewHolder.item_tv_wifi_mac.getText().toString().equals(progress.wifiMac)){ 140 | // myViewHolder.item_pb.setProgress(progress.progress); 141 | // mHomeAdapter.notifyItemChanged(myViewHolder.item_pb.getId()); 142 | // break; 143 | // 144 | // } 145 | 146 | // } 147 | HomeAdapter.MyViewHolder myViewHolder = mholderMap 148 | .get(progress); 149 | if (myViewHolder != null) { 150 | myViewHolder.item_pb.setProgress(progress.progress); 151 | mHomeAdapter.notifyItemChanged(myViewHolder.item_pb 152 | .getId()); 153 | } 154 | break; 155 | case 6 : 156 | 157 | TaskBean overBean = (TaskBean) msg.obj; 158 | // String result = "给" + overBean.ip + "发送文件完成"; 159 | // format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 160 | // .format(System.currentTimeMillis()); 161 | // et_client_msg.append("\n" + format + "-->" 162 | // + result); 163 | updateProgress(overBean, overBean.fileLen); 164 | 165 | // HomeAdapter.MyViewHolder overViewHolder = 166 | // mholderMap.get(overBean); 167 | // if (overViewHolder!=null) { 168 | // DebugLogger.e("设置进度"+overBean.progress); 169 | // overViewHolder.item_pb.setProgress(overBean.progress); 170 | // mHomeAdapter.notifyItemChanged(overViewHolder.item_pb.getId()); 171 | // } 172 | 173 | break; 174 | default : 175 | 176 | break; 177 | } 178 | } 179 | }; 180 | private Button btn_clear; 181 | private Button btn_restart_server; 182 | private Button btn_send; 183 | private EditText et_error_msg; 184 | private String path = ""; 185 | // private ArrayList paths; 186 | private Button btn_send_broadcast; 187 | private ListView list_view; 188 | private ServerAdapter mAdapter; 189 | private HomeAdapter mHomeAdapter; 190 | private RecyclerView mRecyclerView; 191 | private HashMap mholderMap = new HashMap<>(); 192 | private Button btn_clear_dir_broadcast; 193 | private ArrayList mPaths; 194 | 195 | @Override 196 | protected void onCreate(Bundle savedInstanceState) { 197 | super.onCreate(savedInstanceState); 198 | setContentView(R.layout.activity_server); 199 | initView(); 200 | getSupportActionBar().setTitle( 201 | "\t\t" + WifiUtils.getInstance().getParsedIp()); 202 | mAdapter = new ServerAdapter(viewList, mDataList, this); 203 | list_view.setAdapter(mAdapter); 204 | 205 | // 设置布局管理器 206 | // mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 207 | // mRecyclerView.setAdapter(mHomeAdapter = new HomeAdapter()); 208 | // 设置Item增加、移除动画 209 | // mRecyclerView.setItemAnimator(null); 210 | 211 | SocketManager.getInstance().setOnServerListener(this); 212 | } 213 | 214 | @Override 215 | public void onStarted() { 216 | DebugLogger.e("server start ..."); 217 | 218 | String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 219 | .format(System.currentTimeMillis()); 220 | et_client_msg.append("\n" + format + "-->" + "server start ..."); 221 | } 222 | 223 | @Override 224 | public void onStartSend(TaskBean startSend) { 225 | DebugLogger.e("开始发送"); 226 | mDataList.add(startSend); 227 | mAdapter.notifyDataSetChanged(); 228 | list_view.smoothScrollToPosition(mDataList.size() - 1); 229 | } 230 | 231 | @Override 232 | public void onError(Exception ex) { 233 | if (ex instanceof ConnectException) { 234 | Toast.makeText(ServerActivity.this, "连接异常", Toast.LENGTH_SHORT) 235 | .show(); 236 | } 237 | 238 | else { 239 | Toast.makeText(ServerActivity.this, "出现异常", Toast.LENGTH_SHORT) 240 | .show(); 241 | 242 | } 243 | String format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 244 | .format(System.currentTimeMillis()); 245 | et_error_msg.append("\n" + format1 + "-->" 246 | + Log.getStackTraceString(ex)); 247 | } 248 | 249 | @Override 250 | public void onMessage(String msg) { 251 | String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 252 | .format(System.currentTimeMillis()); 253 | et_client_msg.append("\n" + format + "-->" + msg); 254 | } 255 | 256 | @Override 257 | public void onSendFinished(TaskBean sendFinished) { 258 | updateProgress(sendFinished, sendFinished.fileLen); 259 | 260 | } 261 | 262 | @Override 263 | public void onUpdateProgress(TaskBean updateProgress) { 264 | HomeAdapter.MyViewHolder myViewHolder = mholderMap.get(updateProgress); 265 | if (myViewHolder != null) { 266 | myViewHolder.item_pb.setProgress(updateProgress.progress); 267 | mHomeAdapter.notifyItemChanged(myViewHolder.item_pb.getId()); 268 | } 269 | } 270 | 271 | class HomeAdapter extends RecyclerView.Adapter { 272 | 273 | @Override 274 | public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 275 | MyViewHolder holder = new MyViewHolder(LayoutInflater.from( 276 | ServerActivity.this).inflate(R.layout.item_list, parent, 277 | false)); 278 | return holder; 279 | } 280 | 281 | @Override 282 | public void onBindViewHolder(MyViewHolder holder, int position) { 283 | // 设置数据 284 | TaskBean taskBean = mDataList.get(position); 285 | mHolderList.add(holder); 286 | mholderMap.put(taskBean, holder); 287 | holder.item_tv_file_name.setText(taskBean.fileName); 288 | holder.item_tv_ip.setText(taskBean.ip); 289 | holder.item_tv_wifi_mac.setText(taskBean.wifiMac); 290 | int size = taskBean.fileLen / 1024; 291 | if (size == 0) 292 | size += 1; 293 | holder.item_tv_file_len.setText(size + "kb"); 294 | holder.item_pb.setMax(taskBean.fileLen); 295 | } 296 | 297 | @Override 298 | public int getItemCount() { 299 | if (mDataList != null) { 300 | return mDataList.size(); 301 | } 302 | return 0; 303 | } 304 | 305 | class MyViewHolder extends RecyclerView.ViewHolder { 306 | 307 | public TextView item_tv_ip; 308 | public TextView item_tv_wifi_mac; 309 | public TextView item_tv_file_name; 310 | public ProgressBar item_pb; 311 | public TextView item_tv_file_len; 312 | public MyViewHolder(View rootView) { 313 | super(rootView); 314 | this.item_tv_ip = (TextView) rootView 315 | .findViewById(R.id.item_tv_ip); 316 | this.item_tv_wifi_mac = (TextView) rootView 317 | .findViewById(R.id.item_tv_wifi_mac); 318 | this.item_tv_file_name = (TextView) rootView 319 | .findViewById(R.id.item_tv_file_name); 320 | this.item_tv_file_len = (TextView) rootView 321 | .findViewById(R.id.item_tv_file_len); 322 | this.item_pb = (ProgressBar) rootView 323 | .findViewById(R.id.item_pb); 324 | } 325 | } 326 | 327 | } 328 | @Override 329 | protected void onDestroy() { 330 | super.onDestroy(); 331 | SocketManager.getInstance().closeServer(); 332 | } 333 | 334 | private void initView() { 335 | et_client_msg = (EditText) findViewById(R.id.et_client_msg); 336 | btn_clear = (Button) findViewById(R.id.btn_clear); 337 | btn_clear.setOnClickListener(this); 338 | btn_restart_server = (Button) findViewById(R.id.btn_restart_server); 339 | btn_restart_server.setOnClickListener(this); 340 | btn_send = (Button) findViewById(R.id.btn_send); 341 | btn_send.setOnClickListener(this); 342 | et_error_msg = (EditText) findViewById(R.id.et_error_msg); 343 | et_error_msg.setOnClickListener(this); 344 | btn_send_broadcast = (Button) findViewById(R.id.btn_send_broadcast); 345 | btn_send_broadcast.setOnClickListener(this); 346 | list_view = (ListView) findViewById(R.id.list_view); 347 | 348 | // mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); 349 | btn_clear_dir_broadcast = (Button) findViewById(R.id.btn_clear_dir_broadcast); 350 | btn_clear_dir_broadcast.setOnClickListener(this); 351 | } 352 | 353 | private ArrayList viewList = new ArrayList<>(); 354 | public BaseAdapter mBaseAdapter = new BaseAdapter() { 355 | 356 | class ViewHolder { 357 | public View rootView; 358 | public TextView item_tv_ip; 359 | public TextView item_tv_wifi_mac; 360 | public TextView item_tv_file_name; 361 | public TextView item_tv_file_len; 362 | public ProgressBar item_pb; 363 | 364 | public ViewHolder(View rootView) { 365 | this.rootView = rootView; 366 | this.item_tv_ip = (TextView) rootView 367 | .findViewById(R.id.item_tv_ip); 368 | this.item_tv_wifi_mac = (TextView) rootView 369 | .findViewById(R.id.item_tv_wifi_mac); 370 | this.item_tv_file_name = (TextView) rootView 371 | .findViewById(R.id.item_tv_file_name); 372 | this.item_tv_file_len = (TextView) rootView 373 | .findViewById(R.id.item_tv_file_len); 374 | this.item_pb = (ProgressBar) rootView 375 | .findViewById(R.id.item_pb); 376 | } 377 | 378 | } 379 | 380 | @Override 381 | public int getCount() { 382 | if (mDataList != null) { 383 | return mDataList.size(); 384 | } 385 | return 0; 386 | } 387 | 388 | @Override 389 | public Object getItem(int position) { 390 | return mDataList.get(position); 391 | } 392 | 393 | @Override 394 | public long getItemId(int position) { 395 | return position; 396 | } 397 | 398 | @Override 399 | public View getView(int position, View convertView, ViewGroup parent) { 400 | ViewHolder holder = null; 401 | if (convertView == null) { 402 | convertView = View.inflate(ServerActivity.this, 403 | R.layout.item_list, null); 404 | holder = new ViewHolder(convertView); 405 | convertView.setTag(holder); 406 | } else { 407 | holder = (ViewHolder) convertView.getTag(); 408 | } 409 | 410 | // 设置数据 411 | TaskBean taskBean = mDataList.get(position); 412 | convertView.setTag(taskBean.hashCode(), position); 413 | viewList.add(convertView); 414 | holder.item_tv_file_name.setText(taskBean.fileName); 415 | holder.item_tv_ip.setText(taskBean.ip); 416 | holder.item_tv_wifi_mac.setText(taskBean.wifiMac); 417 | int size = taskBean.fileLen / 1024; 418 | if (size == 0) 419 | size += 1; 420 | holder.item_tv_file_len.setText(size + "kb"); 421 | holder.item_pb.setMax(taskBean.fileLen); 422 | return convertView; 423 | } 424 | }; 425 | @Override 426 | public void onClick(View v) { 427 | switch (v.getId()) { 428 | case R.id.btn_clear : 429 | et_error_msg.setText(""); 430 | 431 | break; 432 | case R.id.btn_restart_server : 433 | 434 | SocketManager.getInstance().startServer(mPaths, this); 435 | break; 436 | case R.id.btn_send : 437 | Intent i = new Intent(ServerActivity.this, 438 | FilePickerActivity.class); 439 | i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, true); 440 | i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false); 441 | i.putExtra(FilePickerActivity.EXTRA_MODE, 442 | FilePickerActivity.MODE_FILE); 443 | i.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment 444 | .getExternalStorageDirectory().getPath()); 445 | 446 | startActivityForResult(i, FILE_CODE); 447 | break; 448 | case R.id.btn_send_broadcast : 449 | if (mPaths==null|| mPaths.size() == 0) { 450 | Toast.makeText(ServerActivity.this, "未选择发送文件路径", 451 | Toast.LENGTH_SHORT).show(); 452 | return; 453 | } 454 | // String sendMessage = WifiUtils.getInstance() 455 | // .getParsedIp() 456 | // + "==" 457 | // + file.getName() 458 | // + "==" + file.length(); 459 | BroadcastBean broadcastBean = new BroadcastBean(); 460 | List fileList = new ArrayList<>(); 461 | 462 | for (int j = 0; j < mPaths.size(); j++) { 463 | File file = new File(mPaths.get(j)); 464 | BroadcastBean.FilesBean filesBean = new BroadcastBean.FilesBean( 465 | file.getName(), file.length()); 466 | fileList.add(filesBean); 467 | } 468 | broadcastBean.files = fileList; 469 | broadcastBean.hostIp = WifiUtils.getInstance().getParsedIp(); 470 | broadcastBean.type = BroadcastBean.TYPE_FILE; 471 | String sendMessage = SocketManager.getInstance().parseJson( 472 | broadcastBean); 473 | byte[] sendMSG = sendMessage.getBytes(); 474 | sendBroadcast(sendMSG); 475 | 476 | break; 477 | case R.id.btn_clear_dir_broadcast : 478 | // String msg = "clear"; 479 | BroadcastBean clearBean = new BroadcastBean(); 480 | clearBean.type = BroadcastBean.TYPE_CLEAR; 481 | String json = SocketManager.getInstance().parseJson(clearBean); 482 | sendBroadcast(json.getBytes()); 483 | break; 484 | } 485 | } 486 | 487 | private void sendBroadcast(final byte[] sendMSG) { 488 | // new Thread(new Runnable() { 489 | // @Override 490 | // public void run() { 491 | // 492 | // } 493 | // 494 | // }).start(); 495 | new MulticastThread(sendMSG).start(); 496 | } 497 | 498 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 499 | @Override 500 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 501 | if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) { 502 | if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, 503 | true)) { 504 | // For JellyBean and above 505 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 506 | ClipData clip = data.getClipData(); 507 | mPaths = new ArrayList<>(); 508 | if (clip != null) { 509 | for (int i = 0; i < clip.getItemCount(); i++) { 510 | Uri uri = clip.getItemAt(i).getUri(); 511 | mPaths.add(uri.getPath()); 512 | } 513 | SocketManager.getInstance().startServer(mPaths, 514 | this); 515 | 516 | } 517 | } 518 | // else { 519 | // final ArrayList paths = data 520 | // .getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS); 521 | // final ArrayList fileNames = new ArrayList<>(); 522 | // if (paths != null) { 523 | // for (String path : paths) { 524 | // Uri uri = Uri.parse(path); 525 | // paths.add(uri.getPath()); 526 | // fileNames.add(uri.getLastPathSegment()); 527 | // 528 | // } 529 | // 530 | // } 531 | // } 532 | 533 | } 534 | } 535 | } 536 | 537 | @Override 538 | public void onProgress(TaskBean taskBean, int progress) { 539 | // DebugLogger.d(taskBean.ip + ": " + progress); 540 | 541 | updateProgress(taskBean, progress); 542 | // for (int i = 0; i < mHolderList.size(); i++) { 543 | // HomeAdapter.MyViewHolder myViewHolder = mHolderList.get(i); 544 | // 545 | // if 546 | // (myViewHolder.item_tv_wifi_mac.getText().toString().equals(taskBean.wifiMac)){ 547 | // myViewHolder.item_pb.setProgress(progress); 548 | // mHomeAdapter.notifyItemChanged(myViewHolder.item_pb.getId()); 549 | // break; 550 | // 551 | // } 552 | // } 553 | 554 | } 555 | 556 | private void updateProgress(TaskBean taskBean, int progress) { 557 | View view = null; 558 | for (int i = 0; i < viewList.size(); i++) { 559 | if (viewList.get(i).getTag(taskBean.hashCode()) != null) { 560 | view = viewList.get(i); 561 | break; 562 | } 563 | } 564 | if (view != null) { 565 | ServerAdapter.ViewHolder viewHolder = (ServerAdapter.ViewHolder) view 566 | .getTag(); 567 | viewHolder.item_pb.setProgress(progress); 568 | } 569 | } 570 | } 571 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/ServerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket; 2 | 3 | import android.content.Context; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | import android.widget.BaseAdapter; 7 | import android.widget.ProgressBar; 8 | import android.widget.TextView; 9 | 10 | import com.accvmedia.mysocket.bean.TaskBean; 11 | 12 | import java.util.ArrayList; 13 | 14 | /** 15 | * Created by dempseyZheng on 2017/3/21 16 | */ 17 | public class ServerAdapter extends BaseAdapter { 18 | 19 | 20 | public ServerAdapter(ArrayList viewList, 21 | ArrayList dataList, Context context) 22 | { 23 | this.viewList = viewList; 24 | mDataList = dataList; 25 | mContext = context; 26 | } 27 | 28 | private ArrayList viewList; 29 | private ArrayList mDataList; 30 | private Context mContext; 31 | 32 | 33 | 34 | class ViewHolder { 35 | public View rootView; 36 | public TextView item_tv_ip; 37 | public TextView item_tv_wifi_mac; 38 | public TextView item_tv_file_name; 39 | public ProgressBar item_pb; 40 | public TextView item_tv_file_len; 41 | public ViewHolder(View rootView) { 42 | this.rootView = rootView; 43 | this.item_tv_ip = (TextView) rootView 44 | .findViewById(R.id.item_tv_ip); 45 | this.item_tv_wifi_mac = (TextView) rootView 46 | .findViewById(R.id.item_tv_wifi_mac); 47 | this.item_tv_file_name = (TextView) rootView 48 | .findViewById(R.id.item_tv_file_name); 49 | this.item_tv_file_len = (TextView) rootView 50 | .findViewById(R.id.item_tv_file_len); 51 | this.item_pb = (ProgressBar) rootView 52 | .findViewById(R.id.item_pb); 53 | } 54 | 55 | } 56 | 57 | @Override 58 | public int getCount() { 59 | if (mDataList != null) { 60 | return mDataList.size(); 61 | } 62 | return 0; 63 | } 64 | 65 | @Override 66 | public Object getItem(int position) { 67 | return mDataList.get(position); 68 | } 69 | 70 | @Override 71 | public long getItemId(int position) { 72 | return position; 73 | } 74 | 75 | @Override 76 | public View getView(int position, View convertView, ViewGroup parent) { 77 | ViewHolder holder = null; 78 | if (convertView == null) { 79 | convertView = View.inflate(mContext, 80 | R.layout.item_list, null); 81 | holder = new ViewHolder(convertView); 82 | convertView.setTag(holder); 83 | } else { 84 | holder = (ViewHolder) convertView.getTag(); 85 | } 86 | 87 | // 设置数据 88 | TaskBean taskBean = mDataList.get(position); 89 | convertView.setTag(taskBean.hashCode(),position); 90 | viewList.add(convertView); 91 | holder.item_tv_file_name.setText(taskBean.fileName); 92 | holder.item_tv_ip.setText(taskBean.ip); 93 | holder.item_tv_wifi_mac.setText(taskBean.wifiMac); 94 | int size =taskBean.fileLen/1024; 95 | if (size==0)size+=1; 96 | holder.item_tv_file_len.setText(size+"kb"); 97 | holder.item_pb.setMax(taskBean.fileLen); 98 | return convertView; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/bean/BroadcastBean.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.bean; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Created by dempseyZheng on 2017/3/29 7 | */ 8 | public class BroadcastBean { 9 | 10 | /** 11 | * hostIp : ip 12 | * files : [{"name":"txt","length":"kb"},{"name":"zip","length":"kb"}] 13 | */ 14 | 15 | public String hostIp; 16 | public int type; 17 | /** 18 | * name : txt 19 | * length : kb 20 | */ 21 | 22 | public List files; 23 | 24 | public static final int TYPE_FILE=10001; 25 | public static final int TYPE_CLEAR=10002; 26 | public static class FilesBean { 27 | public String name; 28 | public long length; 29 | 30 | public FilesBean(String name, long length) { 31 | this.name = name; 32 | this.length = length; 33 | } 34 | 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/bean/SocketBean.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.bean; 2 | 3 | /** 4 | * Created by dempseyZheng on 2017/3/29 5 | */ 6 | public class SocketBean { 7 | 8 | /** 9 | * wifiMac : mac 10 | * offset : 0 11 | * file : txt 12 | */ 13 | 14 | public String wifiMac; 15 | public int offset; 16 | public String fileName; 17 | 18 | public SocketBean(String wifiMac, int offset, String fileName) { 19 | this.wifiMac = wifiMac; 20 | this.offset = offset; 21 | this.fileName = fileName; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/bean/TaskBean.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.bean; 2 | 3 | /** 4 | * Created by dempseyZheng on 2017/3/21 5 | */ 6 | public class TaskBean { 7 | public String ip; 8 | public String fileName; 9 | public int fileLen; 10 | public int progress; 11 | 12 | public TaskBean(String ip, String fileName, String wifiMac, int fileLen) { 13 | this.ip = ip; 14 | this.fileName = fileName; 15 | this.wifiMac = wifiMac; 16 | this.fileLen = fileLen; 17 | } 18 | 19 | public String wifiMac; 20 | 21 | @Override 22 | public boolean equals(Object o) { 23 | if (this == o) { 24 | return true; 25 | } 26 | if (o == null || getClass() != o.getClass()) { 27 | return false; 28 | } 29 | 30 | TaskBean taskBean = (TaskBean) o; 31 | 32 | if (fileLen != taskBean.fileLen) { 33 | return false; 34 | } 35 | if (ip != null 36 | ? !ip.equals(taskBean.ip) 37 | : taskBean.ip != null) 38 | { 39 | return false; 40 | } 41 | if (fileName != null 42 | ? !fileName.equals(taskBean.fileName) 43 | : taskBean.fileName != null) 44 | { 45 | return false; 46 | } 47 | return wifiMac != null 48 | ? wifiMac.equals(taskBean.wifiMac) 49 | : taskBean.wifiMac == null; 50 | 51 | } 52 | 53 | @Override 54 | public int hashCode() { 55 | int result = ip != null 56 | ? ip.hashCode() 57 | : 0; 58 | result = 31 * result + (fileName != null 59 | ? fileName.hashCode() 60 | : 0); 61 | result = 31 * result + fileLen; 62 | result = 31 * result + (wifiMac != null 63 | ? wifiMac.hashCode() 64 | : 0); 65 | return result; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/jobqueue/SocketJob.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.jobqueue; 2 | 3 | import android.os.Handler; 4 | import android.os.Message; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.Nullable; 7 | 8 | import com.accvmedia.mysocket.Constant; 9 | import com.accvmedia.mysocket.bean.SocketBean; 10 | import com.accvmedia.mysocket.socket.SocketManager; 11 | import com.accvmedia.mysocket.util.DebugLogger; 12 | import com.accvmedia.mysocket.util.WifiUtils; 13 | import com.birbit.android.jobqueue.Job; 14 | import com.birbit.android.jobqueue.Params; 15 | import com.birbit.android.jobqueue.RetryConstraint; 16 | 17 | import java.io.BufferedInputStream; 18 | import java.io.BufferedOutputStream; 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.FileOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.RandomAccessFile; 25 | import java.net.Socket; 26 | import java.net.SocketTimeoutException; 27 | import java.util.Properties; 28 | 29 | /** 30 | * Created by dempseyZheng on 2017/3/31 31 | */ 32 | public class SocketJob 33 | extends Job { 34 | private int offset; 35 | private Socket socket; 36 | private String mHostIp; 37 | private int mPort; 38 | private Handler mHandler; 39 | private FileCallBack callBack; 40 | private String fileName; 41 | private String mPath=""; 42 | 43 | public interface FileCallBack { 44 | void onProgress(int progress); 45 | 46 | void onStartReceive(String filename, int file_len); 47 | 48 | } 49 | 50 | 51 | public SocketJob(String hostIp, int port,int offset,String fileName, Handler handler, 52 | FileCallBack callBack) { 53 | this(hostIp, port,offset,fileName); 54 | mHandler = handler; 55 | this.callBack = callBack; 56 | 57 | } 58 | public SocketJob(String hostIp, int port,int offset,String fileName) { 59 | super(new Params(Constant.PRIORITY).addTags(fileName).groupBy(Constant.GROUP_ID).requireNetwork()); 60 | mHostIp = hostIp; 61 | mPort = port; 62 | this.fileName=fileName; 63 | this.offset = offset; 64 | } 65 | 66 | 67 | 68 | 69 | 70 | @Override 71 | public void onAdded() { 72 | 73 | } 74 | 75 | @Override 76 | public void onRun() 77 | throws Throwable 78 | { 79 | try { 80 | socket = new Socket(mHostIp, mPort); 81 | // socket.setSoTimeout(30000); 82 | socket.setSoTimeout(Constant.SoTimeout); 83 | if (mHandler != null) 84 | Message.obtain(mHandler, SocketManager.C_CONNECTED, "连接成功") 85 | .sendToTarget(); 86 | 87 | if (socket.isConnected()) { 88 | if (!socket.isInputShutdown()) { 89 | // String sendMsg = WifiUtils.getInstance().getMacAddress() 90 | // + "==" + offset; 91 | 92 | SocketBean bean =new SocketBean(WifiUtils.getInstance().getMacAddress(), offset, fileName); 93 | String sendMsg =SocketManager.getInstance().parseJson(bean); 94 | 95 | SocketManager.getInstance().writeByte(sendMsg.getBytes(), 96 | socket.getOutputStream()); 97 | 98 | InputStream inputStream = socket.getInputStream(); 99 | 100 | readAndSave(inputStream); 101 | 102 | } 103 | } 104 | 105 | // } catch (Exception ex) { 106 | // // Constant.isReceiving=false; 107 | // if (mHandler != null) { 108 | // Message.obtain(mHandler, SocketManager.C_ERROR, ex) 109 | // .sendToTarget(); 110 | // 111 | // } 112 | // ex.printStackTrace(); 113 | } 114 | finally { 115 | try { 116 | if (socket != null) 117 | socket.close(); 118 | } catch (IOException e) { 119 | e.printStackTrace(); 120 | } 121 | } 122 | } 123 | 124 | @Override 125 | protected void onCancel(int cancelReason, @Nullable Throwable throwable) { 126 | DebugLogger.e(cancelReason+"",throwable); 127 | } 128 | 129 | @Override 130 | protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, 131 | int runCount, 132 | int maxRunCount) 133 | { 134 | if (throwable instanceof SocketTimeoutException) { 135 | DebugLogger.e("retry"); 136 | offset=getOffset(new File(mPath + ".log")); 137 | return RetryConstraint.RETRY; 138 | } 139 | return RetryConstraint.CANCEL; 140 | } 141 | 142 | private int getOffset(File file) { 143 | int position = 0; 144 | if (file.exists()) { 145 | Properties properties = new Properties(); 146 | try { 147 | properties.load(new FileInputStream(file)); 148 | } catch (IOException e) { 149 | e.printStackTrace(); 150 | } 151 | position = Integer.valueOf(properties.getProperty("length"));// 读取断点的位置 152 | } 153 | return position; 154 | } 155 | // 从流中读取内容并保存 156 | private void readAndSave(InputStream is) throws IOException { 157 | Constant.isReceiving = true; 158 | String filename = SocketManager.getInstance().readByte(is); 159 | int file_len = SocketManager.getInstance().readInteger(is); 160 | DebugLogger.i("接收文件:" + filename + ",长度:" + file_len); 161 | // String receivePath = Constant.RECEIVE_FILE_DIR+"/"+filename; 162 | // if (isFileReceived(receivePath,file_len)){ 163 | // Message.obtain(mHandler,5,"文件已接收过,路径为: "+receivePath).sendToTarget(); 164 | // socket.close(); 165 | // return; 166 | // } 167 | if (callBack != null) { 168 | callBack.onStartReceive(filename, file_len); 169 | } 170 | 171 | int fileSize = file_len / 1024; 172 | if (fileSize == 0) { 173 | fileSize = 1; 174 | } 175 | String startReceive = "开始接收文件,文件名: " + filename + "文件大小: " + fileSize 176 | + "kb"; 177 | Message.obtain(mHandler, SocketManager.C_MESSAGE, startReceive) 178 | .sendToTarget(); 179 | 180 | File dir = new File(Constant.RECEIVE_FILE_DIR); 181 | if (!dir.exists()) 182 | dir.mkdir(); 183 | readAndSave0(is, Constant.RECEIVE_FILE_DIR + "/" + filename, file_len); 184 | String msg = "文件保存成功(" + file_len / 1024 + "kb)。"; 185 | 186 | DebugLogger.e(msg); 187 | Constant.isReceiving = false; 188 | 189 | } 190 | 191 | private void readAndSave0(InputStream is, String path, int file_len) 192 | throws IOException { 193 | 194 | // Constant.RECEIVE_FILE_PATH = path; 195 | mPath= path; 196 | 197 | // FileOutputStream os = getFileOS(path); 198 | // readAndWrite(is, os, file_len); 199 | // os.close(); 200 | File file = new File(path); 201 | 202 | RandomAccessFile raf = getRandomAccessFile(file); 203 | 204 | readAndWrite(is, raf, file_len, file); 205 | if (mHandler != null) 206 | Message.obtain(mHandler, SocketManager.C_RECEIVE_FINISHED, path) 207 | .sendToTarget(); 208 | } 209 | 210 | private RandomAccessFile getRandomAccessFile(File file) throws IOException { 211 | RandomAccessFile raf = new RandomAccessFile(file, "rw"); 212 | if (!file.exists()) { 213 | file.createNewFile(); 214 | } else { 215 | raf.seek(file.length()); 216 | } 217 | return raf; 218 | } 219 | 220 | // 创建文件并返回输出流 221 | private FileOutputStream getFileOS(String path) throws IOException { 222 | File file = new File(path); 223 | if (!file.exists()) { 224 | file.createNewFile(); 225 | } 226 | 227 | return new FileOutputStream(file); 228 | } 229 | 230 | // 边读边写,直到读取 size 个字节 231 | private void readAndWrite(InputStream is, FileOutputStream os, int size) 232 | throws IOException { 233 | BufferedOutputStream bos = new BufferedOutputStream(os, 1024 * 200); 234 | 235 | BufferedInputStream bis = new BufferedInputStream(is, 1024 * 200); 236 | byte[] buffer = new byte[4096]; 237 | int count = 0; 238 | while (count < size) { 239 | // int n = is.read(buffer); 240 | // // 这里没有考虑 n = -1 的情况 241 | // os.write(buffer, 0, n); 242 | int n = bis.read(buffer); 243 | bos.write(buffer, 0, n); 244 | count += n; 245 | if (callBack != null) 246 | callBack.onProgress(count); 247 | } 248 | bos.flush(); 249 | } 250 | 251 | private void readAndWrite(InputStream is, RandomAccessFile raf, int size, 252 | File file) throws IOException { 253 | 254 | BufferedInputStream bis = new BufferedInputStream(is, 1024 * 200); 255 | byte[] buffer = new byte[4096]; 256 | // int count = 0; 257 | int count = offset; 258 | 259 | Properties properties = new Properties(); 260 | FileOutputStream fileOutputStream = new FileOutputStream(new File( 261 | file.getParent(), file.getName() + ".log"), false); 262 | 263 | while (count < size) { 264 | // int n = is.read(buffer); 265 | // // 这里没有考虑 n = -1 的情况 266 | // os.write(buffer, 0, n); 267 | int n = bis.read(buffer); 268 | raf.write(buffer, 0, n); 269 | count += n; 270 | properties.put("length", String.valueOf(count)); 271 | 272 | properties.store(fileOutputStream, null);// 实时记录文件的最后保存位置 273 | 274 | if (callBack != null) 275 | callBack.onProgress(count); 276 | } 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/jobqueue/SocketJobManager.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.jobqueue; 2 | 3 | import android.content.Context; 4 | import android.support.annotation.NonNull; 5 | import android.support.annotation.Nullable; 6 | import android.util.Log; 7 | 8 | import com.accvmedia.mysocket.util.DebugLogger; 9 | import com.birbit.android.jobqueue.AsyncAddCallback; 10 | import com.birbit.android.jobqueue.Job; 11 | import com.birbit.android.jobqueue.JobManager; 12 | import com.birbit.android.jobqueue.callback.JobManagerCallback; 13 | import com.birbit.android.jobqueue.config.Configuration; 14 | import com.birbit.android.jobqueue.log.CustomLogger; 15 | 16 | import java.util.Set; 17 | 18 | /** 19 | * Created by dempseyZheng on 2017/3/31 20 | */ 21 | public class SocketJobManager implements JobManagerCallback { 22 | private static SocketJobManager mSocketJobManager = null; 23 | private JobManager mJobManager; 24 | static { 25 | mSocketJobManager = new SocketJobManager(); 26 | } 27 | 28 | public static SocketJobManager getInstance() { 29 | return mSocketJobManager; 30 | } 31 | 32 | public void init(Context context) { 33 | Configuration.Builder builder = new Configuration.Builder(context) 34 | .customLogger(new CustomLogger() { 35 | private static final String TAG = "JOBS"; 36 | @Override 37 | public boolean isDebugEnabled() { 38 | return DebugLogger.isDebuggable(); 39 | } 40 | 41 | @Override 42 | public void d(String text, Object... args) { 43 | DebugLogger.d(String.format(text, args)); 44 | } 45 | 46 | @Override 47 | public void e(Throwable t, String text, Object... args) { 48 | DebugLogger.e(String.format(text, args), t); 49 | } 50 | 51 | @Override 52 | public void e(String text, Object... args) { 53 | DebugLogger.e(String.format(text, args)); 54 | } 55 | 56 | @Override 57 | public void v(String text, Object... args) { 58 | DebugLogger.v(String.format(text, args)); 59 | } 60 | }).minConsumerCount(1)// always keep at least one consumer alive 61 | .maxConsumerCount(1)// up to 3 consumers at a time 62 | .loadFactor(1)// 3 jobs per consumer 63 | .consumerKeepAlive(120);// wait 2 minute 64 | 65 | mJobManager = new JobManager(builder.build()); 66 | mJobManager.addCallback(this); 67 | } 68 | 69 | @Override 70 | public void onJobAdded(@NonNull Job job) { 71 | Set tags = job.getTags(); 72 | for (String tag : tags) { 73 | Log.e("Dempsey", "onJobAdded: " + tag); 74 | } 75 | } 76 | 77 | @Override 78 | public void onJobRun(@NonNull Job job, int resultCode) { 79 | 80 | } 81 | 82 | @Override 83 | public void onJobCancelled(@NonNull Job job, boolean byCancelRequest, 84 | @Nullable Throwable throwable) { 85 | 86 | } 87 | 88 | @Override 89 | public void onDone(@NonNull Job job) { 90 | Set tags = job.getTags(); 91 | for (String tag : tags) { 92 | Log.e("Dempsey", "onDone: " + tag); 93 | } 94 | } 95 | 96 | @Override 97 | public void onAfterJobRun(@NonNull Job job, int resultCode) { 98 | 99 | } 100 | 101 | public void addJobInBackground(Job job, final AsyncAddCallback callback) { 102 | if (mJobManager != null) { 103 | mJobManager.addJobInBackground(job, callback); 104 | } 105 | } 106 | 107 | public void addJobInBackground(Job job) { 108 | if (mJobManager != null) { 109 | mJobManager.addJobInBackground(job); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/receiver/WifiChangedReceiver.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.receiver; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.net.NetworkInfo; 7 | import android.net.wifi.WifiManager; 8 | import android.os.Parcelable; 9 | import android.util.Log; 10 | 11 | /** 12 | * Created by Administrator on 2016/11/24 0024. 13 | */ 14 | 15 | public class WifiChangedReceiver extends BroadcastReceiver { 16 | private static final boolean DEBUG = true; 17 | 18 | @Override 19 | public void onReceive(Context context, Intent intent) { 20 | 21 | if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { 22 | Parcelable parcelableExtra = intent 23 | .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 24 | if (null != parcelableExtra) { 25 | NetworkInfo networkInfo = (NetworkInfo) parcelableExtra; 26 | NetworkInfo.State state = networkInfo.getState(); 27 | switch (state) { 28 | case CONNECTED : 29 | // SocketManager.getInstance().newClient(Constant.HOST_IP, 30 | // Constant.PORT); 31 | break; 32 | 33 | case DISCONNECTED : 34 | 35 | break; 36 | } 37 | } 38 | } 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/socket/ClientThread.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.socket; 2 | 3 | import android.os.Handler; 4 | import android.os.Message; 5 | 6 | import com.accvmedia.mysocket.Constant; 7 | import com.accvmedia.mysocket.bean.SocketBean; 8 | import com.accvmedia.mysocket.util.DebugLogger; 9 | import com.accvmedia.mysocket.util.WifiUtils; 10 | 11 | import java.io.BufferedInputStream; 12 | import java.io.BufferedOutputStream; 13 | import java.io.File; 14 | import java.io.FileOutputStream; 15 | import java.io.IOException; 16 | import java.io.InputStream; 17 | import java.io.RandomAccessFile; 18 | import java.net.Socket; 19 | import java.util.Properties; 20 | 21 | /** 22 | * Created by dempseyZheng on 2017/3/15 23 | */ 24 | public class ClientThread extends Thread { 25 | private int offset; 26 | private Socket socket; 27 | private String mHostIp; 28 | private int mPort; 29 | private Handler mHandler; 30 | private FileCallBack callBack; 31 | private String fileName; 32 | 33 | public ClientThread(String hostIp, int port, int offset,String name, Handler handler, 34 | FileCallBack callBack) { 35 | this(hostIp, port, name,handler, callBack); 36 | this.offset = offset; 37 | } 38 | 39 | public interface FileCallBack { 40 | void onProgress(int progress); 41 | 42 | void onStartReceive(String filename, int file_len); 43 | 44 | } 45 | 46 | public ClientThread(String hostIp, int port,String fileName, Handler handler, 47 | FileCallBack callBack) { 48 | this(hostIp, port); 49 | mHandler = handler; 50 | this.callBack = callBack; 51 | this.fileName=fileName; 52 | } 53 | public ClientThread(String hostIp, int port) { 54 | mHostIp = hostIp; 55 | mPort = port; 56 | } 57 | @Override 58 | public void run() { 59 | try { 60 | socket = new Socket(mHostIp, mPort); 61 | // socket.setSoTimeout(30000); 62 | socket.setSoTimeout(1000 * 10); 63 | if (mHandler != null) 64 | Message.obtain(mHandler, SocketManager.C_CONNECTED, "连接成功") 65 | .sendToTarget(); 66 | 67 | if (socket.isConnected()) { 68 | if (!socket.isInputShutdown()) { 69 | // String sendMsg = WifiUtils.getInstance().getMacAddress() 70 | // + "==" + offset; 71 | 72 | SocketBean bean=new SocketBean(WifiUtils.getInstance().getMacAddress(),offset,fileName); 73 | String sendMsg =SocketManager.getInstance().parseJson(bean); 74 | 75 | SocketManager.getInstance().writeByte(sendMsg.getBytes(), 76 | socket.getOutputStream()); 77 | 78 | 79 | 80 | 81 | InputStream inputStream = socket.getInputStream(); 82 | 83 | readAndSave(inputStream); 84 | 85 | } 86 | } 87 | 88 | } catch (Exception ex) { 89 | // Constant.isReceiving=false; 90 | if (mHandler != null) { 91 | Message.obtain(mHandler, SocketManager.C_ERROR, ex) 92 | .sendToTarget(); 93 | 94 | } 95 | ex.printStackTrace(); 96 | } finally { 97 | try { 98 | if (socket != null) 99 | socket.close(); 100 | } catch (IOException e) { 101 | e.printStackTrace(); 102 | } 103 | } 104 | 105 | } 106 | 107 | // 从流中读取内容并保存 108 | private void readAndSave(InputStream is) throws IOException { 109 | Constant.isReceiving = true; 110 | String filename = SocketManager.getInstance().readByte(is); 111 | int file_len = SocketManager.getInstance().readInteger(is); 112 | DebugLogger.i("接收文件:" + filename + ",长度:" + file_len); 113 | // String receivePath = Constant.RECEIVE_FILE_DIR+"/"+filename; 114 | // if (isFileReceived(receivePath,file_len)){ 115 | // Message.obtain(mHandler,5,"文件已接收过,路径为: "+receivePath).sendToTarget(); 116 | // socket.close(); 117 | // return; 118 | // } 119 | if (callBack != null) { 120 | callBack.onStartReceive(filename, file_len); 121 | } 122 | 123 | int fileSize = file_len / 1024; 124 | if (fileSize == 0) { 125 | fileSize = 1; 126 | } 127 | String startReceive = "开始接收文件,文件名: " + filename + "文件大小: " + fileSize 128 | + "kb"; 129 | Message.obtain(mHandler, SocketManager.C_MESSAGE, startReceive) 130 | .sendToTarget(); 131 | 132 | File dir = new File(Constant.RECEIVE_FILE_DIR); 133 | if (!dir.exists()) 134 | dir.mkdir(); 135 | readAndSave0(is, Constant.RECEIVE_FILE_DIR + "/" + filename, file_len); 136 | String msg = "文件保存成功(" + file_len / 1024 + "kb)。"; 137 | 138 | DebugLogger.e(msg); 139 | Constant.isReceiving = false; 140 | 141 | } 142 | 143 | private void readAndSave0(InputStream is, String path, int file_len) 144 | throws IOException { 145 | 146 | Constant.RECEIVE_FILE_PATH = path; 147 | 148 | // FileOutputStream os = getFileOS(path); 149 | // readAndWrite(is, os, file_len); 150 | // os.close(); 151 | File file = new File(path); 152 | 153 | RandomAccessFile raf = getRandomAccessFile(file); 154 | 155 | readAndWrite(is, raf, file_len, file); 156 | if (mHandler != null) 157 | Message.obtain(mHandler, SocketManager.C_RECEIVE_FINISHED, path) 158 | .sendToTarget(); 159 | } 160 | 161 | private RandomAccessFile getRandomAccessFile(File file) throws IOException { 162 | RandomAccessFile raf = new RandomAccessFile(file, "rw"); 163 | if (!file.exists()) { 164 | file.createNewFile(); 165 | } else { 166 | raf.seek(file.length()); 167 | } 168 | return raf; 169 | } 170 | 171 | // 创建文件并返回输出流 172 | private FileOutputStream getFileOS(String path) throws IOException { 173 | File file = new File(path); 174 | if (!file.exists()) { 175 | file.createNewFile(); 176 | } 177 | 178 | return new FileOutputStream(file); 179 | } 180 | 181 | // 边读边写,直到读取 size 个字节 182 | private void readAndWrite(InputStream is, FileOutputStream os, int size) 183 | throws IOException { 184 | BufferedOutputStream bos = new BufferedOutputStream(os, 1024 * 200); 185 | 186 | BufferedInputStream bis = new BufferedInputStream(is, 1024 * 200); 187 | byte[] buffer = new byte[4096]; 188 | int count = 0; 189 | while (count < size) { 190 | // int n = is.read(buffer); 191 | // // 这里没有考虑 n = -1 的情况 192 | // os.write(buffer, 0, n); 193 | int n = bis.read(buffer); 194 | bos.write(buffer, 0, n); 195 | count += n; 196 | if (callBack != null) 197 | callBack.onProgress(count); 198 | } 199 | bos.flush(); 200 | } 201 | 202 | private void readAndWrite(InputStream is, RandomAccessFile raf, int size, 203 | File file) throws IOException { 204 | 205 | BufferedInputStream bis = new BufferedInputStream(is, 1024 * 200); 206 | byte[] buffer = new byte[4096]; 207 | // int count = 0; 208 | int count = offset; 209 | 210 | Properties properties = new Properties(); 211 | FileOutputStream fileOutputStream = new FileOutputStream(new File( 212 | file.getParent(), file.getName() + ".log"), false); 213 | 214 | while (count < size) { 215 | // int n = is.read(buffer); 216 | // // 这里没有考虑 n = -1 的情况 217 | // os.write(buffer, 0, n); 218 | int n = bis.read(buffer); 219 | raf.write(buffer, 0, n); 220 | count += n; 221 | properties.put("length", String.valueOf(count)); 222 | 223 | properties.store(fileOutputStream, null);// 实时记录文件的最后保存位置 224 | 225 | if (callBack != null) 226 | callBack.onProgress(count); 227 | } 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/socket/MulticastThread.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.socket; 2 | 3 | import com.accvmedia.mysocket.Constant; 4 | import com.accvmedia.mysocket.util.DebugLogger; 5 | 6 | import java.io.IOException; 7 | import java.net.DatagramPacket; 8 | import java.net.InetAddress; 9 | import java.net.MulticastSocket; 10 | 11 | /** 12 | * Created by dempseyZheng on 2017/3/27 13 | */ 14 | public class MulticastThread 15 | extends Thread { 16 | private byte[] mSendMSG; 17 | 18 | public MulticastThread(byte[] sendMSG) { 19 | 20 | mSendMSG = sendMSG; 21 | } 22 | 23 | @Override 24 | public void run() { 25 | try { 26 | InetAddress broadAddress = InetAddress 27 | .getByName(Constant.multicastHost); 28 | if (!broadAddress.isMulticastAddress()) {// 测试是否为多播地址 29 | // throw new RuntimeException("请使用多播地址"); 30 | DebugLogger.e("请使用多播地址"); 31 | } 32 | MulticastSocket multiSocket = new MulticastSocket(); 33 | multiSocket.setTimeToLive(4); 34 | 35 | 36 | DatagramPacket dp = new DatagramPacket(mSendMSG, 37 | mSendMSG.length, broadAddress, 38 | Constant.multicastPort); 39 | 40 | multiSocket.send(dp); 41 | 42 | multiSocket.close(); 43 | } catch (IOException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/socket/ServerRunnable.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.socket; 2 | 3 | import android.os.Handler; 4 | import android.os.Message; 5 | import android.os.SystemClock; 6 | 7 | import com.accvmedia.mysocket.Constant; 8 | import com.accvmedia.mysocket.bean.SocketBean; 9 | import com.accvmedia.mysocket.bean.TaskBean; 10 | import com.accvmedia.mysocket.util.DebugLogger; 11 | 12 | import java.io.BufferedOutputStream; 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | import java.io.OutputStream; 17 | import java.io.RandomAccessFile; 18 | import java.net.Socket; 19 | import java.util.ArrayList; 20 | 21 | /** 22 | * Created by dempseyZheng on 2017/3/15 23 | */ 24 | public class ServerRunnable implements Runnable { 25 | private Socket socket; 26 | private Handler mHandler; 27 | private ArrayList mFileNames; 28 | private String mPath; 29 | private String ip; 30 | private String mWifiMac; 31 | private ProgressCallBack mCallBack; 32 | private TaskBean mTaskBean; 33 | private int offset; 34 | private String fileName; 35 | 36 | public interface ProgressCallBack { 37 | void onProgress(TaskBean taskBean, int progress); 38 | } 39 | public ServerRunnable(Socket socket, Handler handler, String path, 40 | ProgressCallBack callBack) { 41 | mCallBack = callBack; 42 | this.socket = socket; 43 | mHandler = handler; 44 | mPath = path; 45 | this.ip = socket.getInetAddress().getHostAddress(); 46 | } 47 | public ServerRunnable(Socket socket, Handler handler, 48 | ArrayList fileNames, ProgressCallBack callBack) { 49 | this.socket = socket; 50 | mHandler = handler; 51 | mFileNames = fileNames; 52 | this.ip = socket.getInetAddress().getHostAddress(); 53 | mCallBack = callBack; 54 | } 55 | 56 | 57 | @Override 58 | public void run() { 59 | try { 60 | // if (mFileNames!=null){ 61 | // sendFile(socket.getOutputStream(),mFileNames); 62 | // }else{ 63 | // 64 | // sendFile(socket.getOutputStream(), mPath); 65 | // } 66 | // 拿到连接的mac地址 67 | InputStream inputStream = socket.getInputStream(); 68 | String recMsg = SocketManager.getInstance().readByte(inputStream); 69 | 70 | 71 | 72 | // String[] split = recMsg.split("=="); 73 | // if (split.length > 0) { 74 | // mWifiMac = split[0]; 75 | // offset = Integer.valueOf(split[1]); 76 | // } 77 | 78 | //解析客户端数据 79 | SocketBean socketBean=SocketManager.getInstance().fromJson(recMsg); 80 | mWifiMac=socketBean.wifiMac; 81 | offset=socketBean.offset; 82 | fileName = socketBean.fileName; 83 | DebugLogger.e(mWifiMac+"=="+offset+"=="+fileName); 84 | File file=new File(Constant.SEND_DIR); 85 | 86 | if (!file.exists())file.mkdir(); 87 | 88 | String path = Constant.SEND_DIR+"/"+fileName; 89 | 90 | if (mHandler != null) 91 | Message.obtain(mHandler, SocketManager.S_MESSAGE, 92 | ip + "的wifiMac: " + mWifiMac).sendToTarget(); 93 | sendFile(socket.getOutputStream(), path); 94 | 95 | } catch (Exception e) { 96 | if (mHandler != null) 97 | Message.obtain(mHandler, SocketManager.S_ERROR, e) 98 | .sendToTarget(); 99 | e.printStackTrace(); 100 | } 101 | } 102 | 103 | 104 | 105 | 106 | public void sendFile(OutputStream os, String filepath) throws IOException { 107 | 108 | File file = new File(filepath); 109 | // FileInputStream is = new FileInputStream(filepath); 110 | RandomAccessFile raf = new RandomAccessFile(file, "rw"); 111 | try { 112 | int length = (int) file.length(); 113 | String msg = "给" + ip + "发送文件:" + file.getName() + ",长度:" + length; 114 | DebugLogger.i(msg); 115 | mTaskBean = new TaskBean(ip, file.getName(), mWifiMac, length); 116 | 117 | Message.obtain(mHandler, SocketManager.S_START_SEND, mTaskBean) 118 | .sendToTarget(); 119 | // 发送文件名和文件内容 120 | // writeFileName(file, os); 121 | SocketManager.getInstance() 122 | .writeByte(file.getName().getBytes(), os); 123 | 124 | // writeFileContent(is, os, length); 125 | writeFileContent(raf, os, length); 126 | } finally { 127 | os.close(); 128 | raf.close(); 129 | } 130 | } 131 | 132 | // public void sendFile(OutputStream os, ArrayList filepaths) 133 | // throws IOException { 134 | // for (int i = 0; i < filepaths.size(); i++) { 135 | // String filePath = filepaths.get(i); 136 | // 137 | // File file = new File(filePath); 138 | // FileInputStream is = new FileInputStream(filePath); 139 | // 140 | // try { 141 | // int length = (int) file.length(); 142 | // DebugLogger.i("给" + ip + "发送文件:" + file.getName() + ",长度:" 143 | // + length); 144 | // 145 | // // 发送文件名和文件内容 146 | // writeFileName(file, os); 147 | // writeFileContent(is, os, length); 148 | // } finally { 149 | // os.close(); 150 | // is.close(); 151 | // } 152 | // 153 | // } 154 | // 155 | // } 156 | 157 | // 输出文件内容 158 | // private void writeFileContent(InputStream is, OutputStream os, int 159 | // length) 160 | // throws IOException { 161 | // // 输出文件长度 162 | // os.write(SocketManager.getInstance().i2b(length)); 163 | // 164 | // BufferedInputStream bis = new BufferedInputStream(is,1024*200); 165 | // BufferedOutputStream bos = new BufferedOutputStream(os,1024*200); 166 | // 167 | // // 输出文件内容 168 | // byte[] buffer = new byte[4096]; 169 | // int size; 170 | // long progress = 0; 171 | // // int buf=0; 172 | // long startTime = System.currentTimeMillis(); 173 | // // while ((size = is.read(buffer)) != -1) { 174 | // // os.write(buffer, 0, size); 175 | // // progress += size; 176 | // // DebugLogger.d(ip + ": " + progress); 177 | // // buf+=size; 178 | // // if (buf>4096){ 179 | // // buf=0; 180 | // // } 181 | // // if (mCallBack!=null){ 182 | // // mCallBack.onProgress(mTaskBean, (int) progress); 183 | // // } 184 | // 185 | // // if (mHandler!=null){ 186 | // // mTaskBean.progress= (int) progress; 187 | // // Message.obtain(mHandler,5,mTaskBean).sendToTarget(); 188 | // // } 189 | // 190 | // // } 191 | // while ((size = bis.read(buffer)) != -1) { 192 | // bos.write(buffer, 0, size); 193 | // progress += size; 194 | // DebugLogger.d(ip + ": " + progress); 195 | // if (mCallBack != null) { 196 | // mCallBack.onProgress(mTaskBean, (int) progress); 197 | // } 198 | // } 199 | // bos.flush(); 200 | // long costTime = System.currentTimeMillis() - startTime; 201 | // int costSecond = (int) (costTime / 1000); 202 | // if (costSecond == 0) { 203 | // costSecond = 1; 204 | // } 205 | // 206 | // SystemClock.sleep(500); 207 | // String result = "给" + ip + "发送文件完成,耗时:" + costSecond + "秒,下载速度:" 208 | // + length / 1024 / costSecond + "kb/秒"; 209 | // DebugLogger.e(result); 210 | // if (mHandler != null) { 211 | // Message.obtain(mHandler, SocketManager.S_MESSAGE, result).sendToTarget(); 212 | // mTaskBean.progress = length; 213 | // Message.obtain(mHandler, SocketManager.S_SEND_FINISHED, 214 | // mTaskBean).sendToTarget(); 215 | // 216 | // } 217 | // socket.close(); 218 | // } 219 | 220 | private void writeFileContent(RandomAccessFile raf, OutputStream os, 221 | int length) throws IOException { 222 | // 输出文件长度 223 | os.write(SocketManager.getInstance().i2b(length)); 224 | raf.seek(offset); 225 | DebugLogger.e("文件位置:" + offset); 226 | BufferedOutputStream bos = new BufferedOutputStream(os, 1024 * 200); 227 | 228 | // 输出文件内容 229 | byte[] buffer = new byte[4096]; 230 | int size; 231 | long progress = 0; 232 | // int buf=0; 233 | long startTime = System.currentTimeMillis(); 234 | 235 | while ((size = raf.read(buffer)) != -1) { 236 | bos.write(buffer, 0, size); 237 | progress += size; 238 | DebugLogger.d(ip + ": " + progress); 239 | if (mCallBack != null) { 240 | mCallBack.onProgress(mTaskBean, (int) progress); 241 | } 242 | } 243 | bos.flush(); 244 | long costTime = System.currentTimeMillis() - startTime; 245 | int costSecond = (int) (costTime / 1000); 246 | if (costSecond == 0) { 247 | costSecond = 1; 248 | } 249 | int kbLen = length / 1024; 250 | if (kbLen == 0) { 251 | kbLen = 1; 252 | } 253 | SystemClock.sleep(500); 254 | String result = "给" + ip + "发送文件完成,耗时:" + costSecond + "秒,下载速度:" 255 | + kbLen / costSecond + "kb/秒"; 256 | DebugLogger.e(result); 257 | if (mHandler != null) { 258 | Message.obtain(mHandler, SocketManager.S_MESSAGE, result) 259 | .sendToTarget(); 260 | mTaskBean.progress = length; 261 | Message.obtain(mHandler, SocketManager.S_SEND_FINISHED, mTaskBean) 262 | .sendToTarget(); 263 | 264 | } 265 | socket.close(); 266 | } 267 | 268 | 269 | } 270 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/socket/SocketManager.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.socket; 2 | 3 | import android.os.Handler; 4 | import android.os.Message; 5 | 6 | import com.accvmedia.mysocket.Constant; 7 | import com.accvmedia.mysocket.bean.BroadcastBean; 8 | import com.accvmedia.mysocket.bean.SocketBean; 9 | import com.accvmedia.mysocket.bean.TaskBean; 10 | import com.accvmedia.mysocket.jobqueue.SocketJob; 11 | import com.accvmedia.mysocket.jobqueue.SocketJobManager; 12 | import com.accvmedia.mysocket.util.DebugLogger; 13 | import com.google.gson.Gson; 14 | 15 | import java.io.File; 16 | import java.io.IOException; 17 | import java.io.InputStream; 18 | import java.io.OutputStream; 19 | import java.net.ConnectException; 20 | import java.net.DatagramPacket; 21 | import java.net.InetAddress; 22 | import java.net.MulticastSocket; 23 | import java.net.ServerSocket; 24 | import java.net.Socket; 25 | import java.net.SocketTimeoutException; 26 | import java.util.ArrayList; 27 | import java.util.concurrent.ExecutorService; 28 | import java.util.concurrent.Executors; 29 | 30 | /** 31 | * Created by dempseyZheng on 2017/3/15 32 | */ 33 | public class SocketManager { 34 | private static SocketManager mSocketManager = null; 35 | static { 36 | mSocketManager = new SocketManager(); 37 | } 38 | 39 | private ServerSocket server; 40 | private ExecutorService mExecutorService; 41 | private boolean isServerRunning = false; 42 | private boolean isReceiveBroadcast = false; 43 | private String mFilePath; 44 | // private Handler mClientHandler; 45 | private SocketJob.FileCallBack mCallBack; 46 | private MulticastSocket mReceiveMulticast; 47 | private InetAddress mReceiveAddress; 48 | 49 | public static final int C_CONNECTED = 1001; 50 | public static final int C_RECEIVE_FINISHED = 1002; 51 | public static final int C_ERROR = 1003; 52 | public static final int C_MESSAGE = 1004; 53 | public static final int C_BROADCAST_MESSAGE = 1005; 54 | 55 | public static final int S_MESSAGE = 2001; 56 | public static final int S_ERROR = 2002; 57 | public static final int S_STARTED = 2003; 58 | public static final int S_START_SEND = 2004; 59 | public static final int S_UPDATE_PROGRESS = 2005; 60 | public static final int S_SEND_FINISHED = 2006; 61 | 62 | private OnClientListener cListener; 63 | private Gson mGson; 64 | private ArrayList mFilePaths; 65 | 66 | public void setOnClientListener(OnClientListener cListener) { 67 | 68 | this.cListener = cListener; 69 | } 70 | 71 | public String parseJson(Object obj) { 72 | return mGson.toJson(obj); 73 | } 74 | 75 | public SocketBean fromJson(String recMsg) { 76 | 77 | return mGson.fromJson(recMsg,SocketBean.class); 78 | } 79 | 80 | public interface OnClientListener { 81 | void onConnected(); 82 | void onReceiveFinished(String savepath); 83 | void onError(Exception ex); 84 | void onMessage(String msg); 85 | // void onBroadcastMsg(Object obj); 86 | void onBroadcastMsg(BroadcastBean broadcastBean); 87 | } 88 | 89 | private OnServerListener sListener; 90 | public void setOnServerListener(OnServerListener sListener) { 91 | 92 | this.sListener = sListener; 93 | } 94 | public interface OnServerListener { 95 | void onStarted(); 96 | void onStartSend(TaskBean startSend); 97 | void onError(Exception ex); 98 | void onMessage(String msg); 99 | void onSendFinished(TaskBean sendFinished); 100 | void onUpdateProgress(TaskBean updateProgress); 101 | } 102 | public static SocketManager getInstance() { 103 | return mSocketManager; 104 | } 105 | 106 | public void init() { 107 | if (!Constant.isServer) 108 | receiveBroadcast(); 109 | mGson = new Gson(); 110 | 111 | 112 | 113 | } 114 | public Handler mHandler = new Handler() { 115 | public void handleMessage(Message msg) { 116 | super.handleMessage(msg); 117 | switch (msg.what) { 118 | case C_CONNECTED : 119 | if (cListener != null) { 120 | cListener.onConnected(); 121 | } 122 | 123 | break; 124 | case C_RECEIVE_FINISHED : 125 | if (cListener != null) { 126 | cListener.onReceiveFinished((String) msg.obj); 127 | } 128 | 129 | break; 130 | case C_ERROR : 131 | Exception cEx = (Exception) msg.obj; 132 | if (cListener != null) { 133 | cListener.onError(cEx); 134 | } 135 | SocketManager.getInstance().handleClientEx(cEx); 136 | 137 | break; 138 | case C_MESSAGE : 139 | // 显示信息 140 | String info = (String) msg.obj; 141 | if (cListener != null) { 142 | cListener.onMessage(info); 143 | } 144 | 145 | break; 146 | case C_BROADCAST_MESSAGE : 147 | // 收到广播信息 148 | 149 | // String broadMsg = (String) msg.obj; 150 | BroadcastBean broadMsg = (BroadcastBean) msg.obj; 151 | if (cListener != null) { 152 | // cListener.onBroadcastMsg(msg.obj); 153 | cListener.onBroadcastMsg(broadMsg); 154 | } 155 | break; 156 | case S_STARTED : 157 | if (sListener != null) { 158 | sListener.onStarted(); 159 | } 160 | break; 161 | case S_START_SEND : 162 | TaskBean startSend = (TaskBean) msg.obj; 163 | if (sListener != null) { 164 | sListener.onStartSend(startSend); 165 | } 166 | break; 167 | case S_UPDATE_PROGRESS : 168 | TaskBean progress = (TaskBean) msg.obj; 169 | if (sListener != null) { 170 | sListener.onUpdateProgress(progress); 171 | } 172 | break; 173 | case S_MESSAGE : 174 | if (sListener != null) { 175 | sListener.onMessage((String) msg.obj); 176 | } 177 | break; 178 | case S_SEND_FINISHED : 179 | TaskBean overBean = (TaskBean) msg.obj; 180 | if (sListener != null) { 181 | sListener.onSendFinished(overBean); 182 | } 183 | break; 184 | case S_ERROR : 185 | Exception sEx = (Exception) msg.obj; 186 | if (sListener != null) { 187 | sListener.onError(sEx); 188 | } 189 | handleClientEx(sEx); 190 | break; 191 | default : 192 | 193 | break; 194 | } 195 | } 196 | }; 197 | 198 | 199 | 200 | /** 201 | * 启动socket服务器 202 | * 203 | * @param filePath 204 | * 要发送的文件路径 205 | */ 206 | public void startServer(String filePath, 207 | final ServerRunnable.ProgressCallBack callBack) { 208 | mFilePath = filePath; 209 | closeServer(); 210 | new Thread(new Runnable() { 211 | 212 | @Override 213 | public void run() { 214 | try { 215 | server = new ServerSocket(Constant.PORT); 216 | server.setReuseAddress(true); 217 | mExecutorService = Executors.newCachedThreadPool(); 218 | 219 | Message.obtain(mHandler, S_STARTED, "服务器已开启").sendToTarget(); 220 | isServerRunning = true; 221 | Socket client = null; 222 | while (isServerRunning) { 223 | client = server.accept(); 224 | mExecutorService.execute(new ServerRunnable(client, 225 | mHandler, mFilePath, callBack)); 226 | 227 | } 228 | } catch (Exception e) { 229 | e.printStackTrace(); 230 | } 231 | } 232 | }).start(); 233 | } 234 | 235 | 236 | 237 | /** 238 | * 启动socket服务器 239 | * 240 | * @param filePaths 241 | * 要发送的文件路径 242 | */ 243 | public void startServer(ArrayList filePaths, 244 | final ServerRunnable.ProgressCallBack callBack) { 245 | mFilePaths = filePaths; 246 | closeServer(); 247 | new Thread(new Runnable() { 248 | 249 | @Override 250 | public void run() { 251 | try { 252 | server = new ServerSocket(Constant.PORT); 253 | server.setReuseAddress(true); 254 | mExecutorService = Executors.newCachedThreadPool(); 255 | 256 | Message.obtain(mHandler, S_STARTED, "服务器已开启").sendToTarget(); 257 | isServerRunning = true; 258 | Socket client = null; 259 | while (isServerRunning) { 260 | client = server.accept(); 261 | mExecutorService.execute(new ServerRunnable(client, 262 | mHandler, mFilePaths, callBack)); 263 | 264 | } 265 | } catch (Exception e) { 266 | e.printStackTrace(); 267 | } 268 | } 269 | }).start(); 270 | } 271 | 272 | /** 273 | * 关闭socket服务器 274 | */ 275 | public void closeServer() { 276 | isServerRunning = false; 277 | if (server != null) { 278 | try { 279 | server.close(); 280 | server = null; 281 | } catch (IOException e) { 282 | e.printStackTrace(); 283 | } 284 | } 285 | } 286 | 287 | /** 288 | * 创建一个socket客户端 289 | * 290 | * @param hostIp 291 | * 要连接的主机ip地址 292 | * @param port 293 | * 要连接的端口号 294 | * @param path 295 | * 接收的文件路径 296 | * @param fileLen 297 | * 接收的文件字节长度 298 | * @param offset 299 | * 文件写入位置 300 | * @param callBack 301 | * 回调 302 | */ 303 | public void newClient(String hostIp, int port, String path, long fileLen, 304 | int offset, SocketJob.FileCallBack callBack) { 305 | // if (Constant.isReceiving){ 306 | // if (handler!=null) 307 | // Message.obtain(handler,3," 文件正在接收....不要重复接收").sendToTarget(); 308 | // return; 309 | // } 310 | File file = new File(path); 311 | 312 | if (isFileReceived(file, fileLen)) { 313 | if (mHandler != null) 314 | Message.obtain(mHandler, C_MESSAGE, " 文件已经接收过,路径为: " + path) 315 | .sendToTarget(); 316 | return; 317 | } 318 | if (isFileReceiving(file, fileLen)) { 319 | if (mHandler != null) 320 | Message.obtain(mHandler, C_MESSAGE, " 文件正在接收...").sendToTarget(); 321 | return; 322 | } 323 | mCallBack = callBack; 324 | // Message.obtain(mHandler, C_MESSAGE, "开始连接服务器... ").sendToTarget(); 325 | String fileName=file.getName(); 326 | // new ClientThread(hostIp, port, offset, fileName, mHandler, callBack).start(); 327 | SocketJobManager.getInstance().addJobInBackground(new SocketJob(hostIp,port,offset,fileName,mHandler,callBack)); 328 | 329 | } 330 | 331 | private boolean isFileReceiving(File file, long fileLen) { 332 | 333 | if (file.exists() && file.length() != fileLen && Constant.isReceiving) { 334 | return true; 335 | } 336 | return false; 337 | } 338 | 339 | /** 340 | * 创建一个socket客户端 341 | * 342 | * @param hostIp 343 | * 要连接的主机ip地址 344 | * @param port 345 | * 要连接的端口号 346 | */ 347 | public void newClient(String hostIp, int port) { 348 | // new ClientThread(hostIp, port, mClientHandler, mCallBack).start(); 349 | newClient(hostIp, port, "", 0, 0, mCallBack); 350 | } 351 | 352 | public void reconnect(String hostIp, int port) { 353 | if (isFileReceived(new File(Constant.RECEIVE_FILE_PATH), 354 | Constant.RECEIVE_FILE_LENGTH)) { 355 | Message.obtain(mHandler, C_MESSAGE, 356 | " 文件已经接收过,路径为: " + Constant.RECEIVE_FILE_PATH) 357 | .sendToTarget(); 358 | } else { 359 | 360 | newClient(hostIp, port); 361 | } 362 | } 363 | 364 | private boolean isFileReceived(File file, long fileLen) { 365 | 366 | if (file.exists() && file.length() == fileLen) { 367 | return true; 368 | } 369 | return false; 370 | } 371 | 372 | public void onDestroy() { 373 | isReceiveBroadcast = false; 374 | isServerRunning = false; 375 | if (mReceiveMulticast != null && mReceiveAddress != null) { 376 | try { 377 | mReceiveMulticast.leaveGroup(mReceiveAddress); 378 | } catch (IOException e) { 379 | e.printStackTrace(); 380 | } 381 | } 382 | } 383 | 384 | private void receiveBroadcast() { 385 | new Thread(new Runnable() { 386 | @Override 387 | public void run() { 388 | isReceiveBroadcast = true; 389 | try { 390 | 391 | while (isReceiveBroadcast) { 392 | mReceiveAddress = null; 393 | 394 | mReceiveAddress = InetAddress 395 | .getByName(Constant.multicastHost); 396 | 397 | if (!mReceiveAddress.isMulticastAddress()) {// 测试是否为多播地址 398 | 399 | DebugLogger.e("请使用多播地址"); 400 | 401 | } 402 | mReceiveMulticast = new MulticastSocket( 403 | Constant.multicastPort); 404 | mReceiveMulticast.setReuseAddress(true); 405 | mReceiveMulticast.joinGroup(mReceiveAddress); 406 | 407 | DatagramPacket dp = new DatagramPacket(new byte[1024], 408 | 1024); 409 | 410 | mReceiveMulticast.receive(dp); 411 | String msg = new String(dp.getData()).trim(); 412 | BroadcastBean broadcastBean = mGson.fromJson(msg, BroadcastBean.class); 413 | DebugLogger.e(msg); 414 | Message.obtain(mHandler, C_BROADCAST_MESSAGE, broadcastBean).sendToTarget(); 415 | } 416 | } catch (IOException e) { 417 | e.printStackTrace(); 418 | } 419 | } 420 | }).start(); 421 | 422 | } 423 | 424 | // 将 int 转成字节 425 | public byte[] i2b(int i) { 426 | return new byte[]{(byte) ((i >> 24) & 0xFF), (byte) ((i >> 16) & 0xFF), 427 | (byte) ((i >> 8) & 0xFF), (byte) (i & 0xFF)}; 428 | } 429 | 430 | // 输出byte长度和内容 431 | public void writeByte(byte[] bytes, OutputStream os) throws IOException { 432 | os.write(i2b(bytes.length)); // 输出文件名长度 433 | os.write(bytes); // 输出文件名 434 | } 435 | 436 | // 根据byte长度读取内容 437 | public String readByte(InputStream is) throws IOException { 438 | int name_len = readInteger(is); 439 | byte[] result = new byte[name_len]; 440 | is.read(result); 441 | return new String(result); 442 | } 443 | 444 | // 读取一个数字 445 | public int readInteger(InputStream is) throws IOException { 446 | byte[] bytes = new byte[4]; 447 | is.read(bytes); 448 | return b2i(bytes); 449 | } 450 | 451 | // 将字节转成 int。b 长度不得小于 4,且只会取前 4 位。 452 | public int b2i(byte[] b) { 453 | int value = 0; 454 | for (int i = 0; i < 4; i++) { 455 | int shift = (4 - 1 - i) * 8; 456 | value += (b[i] & 0x000000FF) << shift; 457 | } 458 | return value; 459 | } 460 | 461 | public void handleClientEx(Exception ex) { 462 | Constant.isReceiving = false; 463 | if (ex instanceof ConnectException) { 464 | DebugLogger.e("连接异常"); 465 | } else if (ex instanceof SocketTimeoutException) { 466 | DebugLogger.e("连接超时,重连服务器..."); 467 | 468 | } 469 | } 470 | } 471 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/util/DebugLogger.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.util; 2 | 3 | import android.util.Log; 4 | 5 | import com.accvmedia.mysocket.BuildConfig; 6 | 7 | /** 8 | * 日志工具类 在发布时不显示日志 9 | */ 10 | public class DebugLogger { 11 | 12 | static String className; 13 | static String methodName; 14 | static int lineNumber; 15 | 16 | private DebugLogger(){ 17 | /* Protect from instantiations */ 18 | } 19 | 20 | public static boolean isDebuggable() { 21 | return BuildConfig.DEBUG; 22 | } 23 | 24 | private static String createLog(String log ) { 25 | 26 | StringBuffer buffer = new StringBuffer(); 27 | buffer.append("["); 28 | buffer.append(methodName); 29 | buffer.append(":"); 30 | buffer.append(lineNumber); 31 | buffer.append("]"); 32 | buffer.append(log); 33 | 34 | return buffer.toString(); 35 | } 36 | 37 | private static void getMethodNames(StackTraceElement[] sElements){ 38 | className = sElements[1].getFileName(); 39 | methodName = sElements[1].getMethodName(); 40 | lineNumber = sElements[1].getLineNumber(); 41 | } 42 | 43 | public static void e(String message){ 44 | if (!isDebuggable()) 45 | return; 46 | 47 | // Throwable instance must be created before any methods 48 | getMethodNames(new Throwable().getStackTrace()); 49 | Log.e(className, createLog(message)); 50 | } 51 | 52 | public static void i(String message){ 53 | if (!isDebuggable()) 54 | return; 55 | 56 | getMethodNames(new Throwable().getStackTrace()); 57 | Log.i(className, createLog(message)); 58 | } 59 | 60 | public static void d(String message){ 61 | if (!isDebuggable()) 62 | return; 63 | 64 | getMethodNames(new Throwable().getStackTrace()); 65 | Log.d(className, createLog(message)); 66 | } 67 | 68 | public static void v(String message){ 69 | if (!isDebuggable()) 70 | return; 71 | 72 | getMethodNames(new Throwable().getStackTrace()); 73 | Log.v(className, createLog(message)); 74 | } 75 | 76 | public static void w(String message){ 77 | if (!isDebuggable()) 78 | return; 79 | 80 | getMethodNames(new Throwable().getStackTrace()); 81 | Log.w(className, createLog(message)); 82 | } 83 | 84 | public static void wtf(String message){ 85 | if (!isDebuggable()) 86 | return; 87 | 88 | getMethodNames(new Throwable().getStackTrace()); 89 | Log.wtf(className, createLog(message)); 90 | } 91 | 92 | public static void e(String message, Throwable t) { 93 | if (!isDebuggable()) 94 | return; 95 | 96 | // Throwable instance must be created before any methods 97 | getMethodNames(new Throwable().getStackTrace()); 98 | Log.e(className, createLog(message),t); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/util/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.util; 2 | 3 | import android.text.TextUtils; 4 | 5 | import java.io.BufferedInputStream; 6 | import java.io.BufferedOutputStream; 7 | import java.io.BufferedReader; 8 | import java.io.BufferedWriter; 9 | import java.io.File; 10 | import java.io.FileInputStream; 11 | import java.io.FileNotFoundException; 12 | import java.io.FileOutputStream; 13 | import java.io.FileReader; 14 | import java.io.FileWriter; 15 | import java.io.FilenameFilter; 16 | import java.io.IOException; 17 | import java.io.InputStream; 18 | import java.io.InputStreamReader; 19 | import java.io.OutputStream; 20 | import java.security.DigestInputStream; 21 | import java.security.MessageDigest; 22 | import java.security.NoSuchAlgorithmException; 23 | import java.util.ArrayList; 24 | import java.util.Collections; 25 | import java.util.List; 26 | 27 | /** 28 | *
  29 |  *     author: Blankj
  30 |  *     blog  : http://blankj.com
  31 |  *     time  : 2016/8/11
  32 |  *     desc  : 文件相关工具类
  33 |  * 
34 | */ 35 | public class FileUtils { 36 | 37 | private FileUtils() { 38 | throw new UnsupportedOperationException("u can't instantiate me..."); 39 | } 40 | 41 | /** 42 | * 根据文件路径获取文件 43 | * 44 | * @param filePath 文件路径 45 | * @return 文件 46 | */ 47 | public static File getFileByPath(String filePath) { 48 | return TextUtils.isEmpty(filePath) ? null : new File(filePath); 49 | } 50 | 51 | /** 52 | * 判断文件是否存在 53 | * 54 | * @param filePath 文件路径 55 | * @return {@code true}: 存在
{@code false}: 不存在 56 | */ 57 | public static boolean isFileExists(String filePath) { 58 | return isFileExists(getFileByPath(filePath)); 59 | } 60 | 61 | /** 62 | * 判断文件是否存在 63 | * 64 | * @param file 文件 65 | * @return {@code true}: 存在
{@code false}: 不存在 66 | */ 67 | public static boolean isFileExists(File file) { 68 | return file != null && file.exists(); 69 | } 70 | 71 | /** 72 | * 重命名文件 73 | * 74 | * @param filePath 文件路径 75 | * @param newName 新名称 76 | * @return {@code true}: 重命名成功
{@code false}: 重命名失败 77 | */ 78 | public static boolean rename(String filePath, String newName) { 79 | return rename(getFileByPath(filePath), newName); 80 | } 81 | 82 | /** 83 | * 重命名文件 84 | * 85 | * @param file 文件 86 | * @param newName 新名称 87 | * @return {@code true}: 重命名成功
{@code false}: 重命名失败 88 | */ 89 | public static boolean rename(File file, String newName) { 90 | // 文件为空返回false 91 | if (file == null) return false; 92 | // 文件不存在返回false 93 | if (!file.exists()) return false; 94 | // 新的文件名为空返回false 95 | if (TextUtils.isEmpty(newName)) return false; 96 | // 如果文件名没有改变返回true 97 | if (newName.equals(file.getName())) return true; 98 | File newFile = new File(file.getParent() + File.separator + newName); 99 | // 如果重命名的文件已存在返回false 100 | return !newFile.exists() 101 | && file.renameTo(newFile); 102 | } 103 | 104 | /** 105 | * 判断是否是目录 106 | * 107 | * @param dirPath 目录路径 108 | * @return {@code true}: 是
{@code false}: 否 109 | */ 110 | public static boolean isDir(String dirPath) { 111 | return isDir(getFileByPath(dirPath)); 112 | } 113 | 114 | /** 115 | * 判断是否是目录 116 | * 117 | * @param file 文件 118 | * @return {@code true}: 是
{@code false}: 否 119 | */ 120 | public static boolean isDir(File file) { 121 | return isFileExists(file) && file.isDirectory(); 122 | } 123 | 124 | /** 125 | * 判断是否是文件 126 | * 127 | * @param filePath 文件路径 128 | * @return {@code true}: 是
{@code false}: 否 129 | */ 130 | public static boolean isFile(String filePath) { 131 | return isFile(getFileByPath(filePath)); 132 | } 133 | 134 | /** 135 | * 判断是否是文件 136 | * 137 | * @param file 文件 138 | * @return {@code true}: 是
{@code false}: 否 139 | */ 140 | public static boolean isFile(File file) { 141 | return isFileExists(file) && file.isFile(); 142 | } 143 | 144 | /** 145 | * 判断目录是否存在,不存在则判断是否创建成功 146 | * 147 | * @param dirPath 目录路径 148 | * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 149 | */ 150 | public static boolean createOrExistsDir(String dirPath) { 151 | return createOrExistsDir(getFileByPath(dirPath)); 152 | } 153 | 154 | /** 155 | * 判断目录是否存在,不存在则判断是否创建成功 156 | * 157 | * @param file 文件 158 | * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 159 | */ 160 | public static boolean createOrExistsDir(File file) { 161 | // 如果存在,是目录则返回true,是文件则返回false,不存在则返回是否创建成功 162 | return file != null && (file.exists() ? file.isDirectory() : file.mkdirs()); 163 | } 164 | 165 | /** 166 | * 判断文件是否存在,不存在则判断是否创建成功 167 | * 168 | * @param filePath 文件路径 169 | * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 170 | */ 171 | public static boolean createOrExistsFile(String filePath) { 172 | return createOrExistsFile(getFileByPath(filePath)); 173 | } 174 | 175 | /** 176 | * 判断文件是否存在,不存在则判断是否创建成功 177 | * 178 | * @param file 文件 179 | * @return {@code true}: 存在或创建成功
{@code false}: 不存在或创建失败 180 | */ 181 | public static boolean createOrExistsFile(File file) { 182 | if (file == null) return false; 183 | // 如果存在,是文件则返回true,是目录则返回false 184 | if (file.exists()) return file.isFile(); 185 | if (!createOrExistsDir(file.getParentFile())) return false; 186 | try { 187 | return file.createNewFile(); 188 | } catch (IOException e) { 189 | e.printStackTrace(); 190 | return false; 191 | } 192 | } 193 | 194 | /** 195 | * 判断文件是否存在,存在则在创建之前删除 196 | * 197 | * @param filePath 文件路径 198 | * @return {@code true}: 创建成功
{@code false}: 创建失败 199 | */ 200 | public static boolean createFileByDeleteOldFile(String filePath) { 201 | return createFileByDeleteOldFile(getFileByPath(filePath)); 202 | } 203 | 204 | /** 205 | * 判断文件是否存在,存在则在创建之前删除 206 | * 207 | * @param file 文件 208 | * @return {@code true}: 创建成功
{@code false}: 创建失败 209 | */ 210 | public static boolean createFileByDeleteOldFile(File file) { 211 | if (file == null) return false; 212 | // 文件存在并且删除失败返回false 213 | if (file.exists() && file.isFile() && !file.delete()) return false; 214 | // 创建目录失败返回false 215 | if (!createOrExistsDir(file.getParentFile())) return false; 216 | try { 217 | return file.createNewFile(); 218 | } catch (IOException e) { 219 | e.printStackTrace(); 220 | return false; 221 | } 222 | } 223 | 224 | /** 225 | * 复制或移动目录 226 | * 227 | * @param srcDirPath 源目录路径 228 | * @param destDirPath 目标目录路径 229 | * @param isMove 是否移动 230 | * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 231 | */ 232 | private static boolean copyOrMoveDir(String srcDirPath, String destDirPath, boolean isMove) { 233 | return copyOrMoveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath), isMove); 234 | } 235 | 236 | /** 237 | * 复制或移动目录 238 | * 239 | * @param srcDir 源目录 240 | * @param destDir 目标目录 241 | * @param isMove 是否移动 242 | * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 243 | */ 244 | private static boolean copyOrMoveDir(File srcDir, File destDir, boolean isMove) { 245 | if (srcDir == null || destDir == null) return false; 246 | // 如果目标目录在源目录中则返回false,看不懂的话好好想想递归怎么结束 247 | // srcPath : F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res 248 | // destPath: F:\\MyGithub\\AndroidUtilCode\\utilcode\\src\\test\\res1 249 | // 为防止以上这种情况出现出现误判,须分别在后面加个路径分隔符 250 | String srcPath = srcDir.getPath() + File.separator; 251 | String destPath = destDir.getPath() + File.separator; 252 | if (destPath.contains(srcPath)) return false; 253 | // 源文件不存在或者不是目录则返回false 254 | if (!srcDir.exists() || !srcDir.isDirectory()) return false; 255 | // 目标目录不存在返回false 256 | if (!createOrExistsDir(destDir)) return false; 257 | File[] files = srcDir.listFiles(); 258 | for (File file : files) { 259 | File oneDestFile = new File(destPath + file.getName()); 260 | if (file.isFile()) { 261 | // 如果操作失败返回false 262 | if (!copyOrMoveFile(file, oneDestFile, isMove)) return false; 263 | } else if (file.isDirectory()) { 264 | // 如果操作失败返回false 265 | if (!copyOrMoveDir(file, oneDestFile, isMove)) return false; 266 | } 267 | } 268 | return !isMove || deleteDir(srcDir); 269 | } 270 | 271 | /** 272 | * 复制或移动文件 273 | * 274 | * @param srcFilePath 源文件路径 275 | * @param destFilePath 目标文件路径 276 | * @param isMove 是否移动 277 | * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 278 | */ 279 | private static boolean copyOrMoveFile(String srcFilePath, String destFilePath, boolean isMove) { 280 | return copyOrMoveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath), isMove); 281 | } 282 | 283 | /** 284 | * 复制或移动文件 285 | * 286 | * @param srcFile 源文件 287 | * @param destFile 目标文件 288 | * @param isMove 是否移动 289 | * @return {@code true}: 复制或移动成功
{@code false}: 复制或移动失败 290 | */ 291 | private static boolean copyOrMoveFile(File srcFile, File destFile, boolean isMove) { 292 | if (srcFile == null || destFile == null) return false; 293 | // 源文件不存在或者不是文件则返回false 294 | if (!srcFile.exists() || !srcFile.isFile()) return false; 295 | // 目标文件存在且是文件则返回false 296 | if (destFile.exists() && destFile.isFile()) return false; 297 | // 目标目录不存在返回false 298 | if (!createOrExistsDir(destFile.getParentFile())) return false; 299 | try { 300 | return writeFileFromIS(destFile, new FileInputStream(srcFile), false) 301 | && !(isMove && !deleteFile(srcFile)); 302 | } catch (FileNotFoundException e) { 303 | e.printStackTrace(); 304 | return false; 305 | } 306 | } 307 | 308 | /** 309 | * 复制目录 310 | * 311 | * @param srcDirPath 源目录路径 312 | * @param destDirPath 目标目录路径 313 | * @return {@code true}: 复制成功
{@code false}: 复制失败 314 | */ 315 | public static boolean copyDir(String srcDirPath, String destDirPath) { 316 | return copyDir(getFileByPath(srcDirPath), getFileByPath(destDirPath)); 317 | } 318 | 319 | /** 320 | * 复制目录 321 | * 322 | * @param srcDir 源目录 323 | * @param destDir 目标目录 324 | * @return {@code true}: 复制成功
{@code false}: 复制失败 325 | */ 326 | public static boolean copyDir(File srcDir, File destDir) { 327 | return copyOrMoveDir(srcDir, destDir, false); 328 | } 329 | 330 | /** 331 | * 复制文件 332 | * 333 | * @param srcFilePath 源文件路径 334 | * @param destFilePath 目标文件路径 335 | * @return {@code true}: 复制成功
{@code false}: 复制失败 336 | */ 337 | public static boolean copyFile(String srcFilePath, String destFilePath) { 338 | return copyFile(getFileByPath(srcFilePath), getFileByPath(destFilePath)); 339 | } 340 | 341 | /** 342 | * 复制文件 343 | * 344 | * @param srcFile 源文件 345 | * @param destFile 目标文件 346 | * @return {@code true}: 复制成功
{@code false}: 复制失败 347 | */ 348 | public static boolean copyFile(File srcFile, File destFile) { 349 | return copyOrMoveFile(srcFile, destFile, false); 350 | } 351 | 352 | /** 353 | * 移动目录 354 | * 355 | * @param srcDirPath 源目录路径 356 | * @param destDirPath 目标目录路径 357 | * @return {@code true}: 移动成功
{@code false}: 移动失败 358 | */ 359 | public static boolean moveDir(String srcDirPath, String destDirPath) { 360 | return moveDir(getFileByPath(srcDirPath), getFileByPath(destDirPath)); 361 | } 362 | 363 | /** 364 | * 移动目录 365 | * 366 | * @param srcDir 源目录 367 | * @param destDir 目标目录 368 | * @return {@code true}: 移动成功
{@code false}: 移动失败 369 | */ 370 | public static boolean moveDir(File srcDir, File destDir) { 371 | return copyOrMoveDir(srcDir, destDir, true); 372 | } 373 | 374 | /** 375 | * 移动文件 376 | * 377 | * @param srcFilePath 源文件路径 378 | * @param destFilePath 目标文件路径 379 | * @return {@code true}: 移动成功
{@code false}: 移动失败 380 | */ 381 | public static boolean moveFile(String srcFilePath, String destFilePath) { 382 | return moveFile(getFileByPath(srcFilePath), getFileByPath(destFilePath)); 383 | } 384 | 385 | /** 386 | * 移动文件 387 | * 388 | * @param srcFile 源文件 389 | * @param destFile 目标文件 390 | * @return {@code true}: 移动成功
{@code false}: 移动失败 391 | */ 392 | public static boolean moveFile(File srcFile, File destFile) { 393 | return copyOrMoveFile(srcFile, destFile, true); 394 | } 395 | 396 | /** 397 | * 删除目录 398 | * 399 | * @param dirPath 目录路径 400 | * @return {@code true}: 删除成功
{@code false}: 删除失败 401 | */ 402 | public static boolean deleteDir(String dirPath) { 403 | return deleteDir(getFileByPath(dirPath)); 404 | } 405 | 406 | /** 407 | * 删除目录 408 | * 409 | * @param dir 目录 410 | * @return {@code true}: 删除成功
{@code false}: 删除失败 411 | */ 412 | public static boolean deleteDir(File dir) { 413 | if (dir == null) return false; 414 | // 目录不存在返回true 415 | if (!dir.exists()) return true; 416 | // 不是目录返回false 417 | if (!dir.isDirectory()) return false; 418 | // 现在文件存在且是文件夹 419 | File[] files = dir.listFiles(); 420 | if (files != null && files.length != 0) { 421 | for (File file : files) { 422 | if (file.isFile()) { 423 | if (!deleteFile(file)) return false; 424 | } else if (file.isDirectory()) { 425 | if (!deleteDir(file)) return false; 426 | } 427 | } 428 | } 429 | return dir.delete(); 430 | } 431 | 432 | /** 433 | * 删除文件 434 | * 435 | * @param srcFilePath 文件路径 436 | * @return {@code true}: 删除成功
{@code false}: 删除失败 437 | */ 438 | public static boolean deleteFile(String srcFilePath) { 439 | return deleteFile(getFileByPath(srcFilePath)); 440 | } 441 | 442 | /** 443 | * 删除文件 444 | * 445 | * @param file 文件 446 | * @return {@code true}: 删除成功
{@code false}: 删除失败 447 | */ 448 | public static boolean deleteFile(File file) { 449 | return file != null && (!file.exists() || file.isFile() && file.delete()); 450 | } 451 | 452 | /** 453 | * 删除目录下的所有文件 454 | * 455 | * @param dirPath 目录路径 456 | * @return {@code true}: 删除成功
{@code false}: 删除失败 457 | */ 458 | public static boolean deleteFilesInDir(String dirPath) { 459 | return deleteFilesInDir(getFileByPath(dirPath)); 460 | } 461 | 462 | /** 463 | * 删除目录下的所有文件 464 | * 465 | * @param dir 目录 466 | * @return {@code true}: 删除成功
{@code false}: 删除失败 467 | */ 468 | public static boolean deleteFilesInDir(File dir) { 469 | if (dir == null) return false; 470 | // 目录不存在返回true 471 | if (!dir.exists()) return true; 472 | // 不是目录返回false 473 | if (!dir.isDirectory()) return false; 474 | // 现在文件存在且是文件夹 475 | File[] files = dir.listFiles(); 476 | if (files != null && files.length != 0) { 477 | for (File file : files) { 478 | if (file.isFile()) { 479 | if (!deleteFile(file)) return false; 480 | } else if (file.isDirectory()) { 481 | if (!deleteDir(file)) return false; 482 | } 483 | } 484 | } 485 | return true; 486 | } 487 | 488 | /** 489 | * 获取目录下所有文件 490 | * 491 | * @param dirPath 目录路径 492 | * @param isRecursive 是否递归进子目录 493 | * @return 文件链表 494 | */ 495 | public static List listFilesInDir(String dirPath, boolean isRecursive) { 496 | return listFilesInDir(getFileByPath(dirPath), isRecursive); 497 | } 498 | 499 | /** 500 | * 获取目录下所有文件 501 | * 502 | * @param dir 目录 503 | * @param isRecursive 是否递归进子目录 504 | * @return 文件链表 505 | */ 506 | public static List listFilesInDir(File dir, boolean isRecursive) { 507 | if (!isDir(dir)) return null; 508 | if (isRecursive) return listFilesInDir(dir); 509 | List list = new ArrayList<>(); 510 | File[] files = dir.listFiles(); 511 | if (files != null && files.length != 0) { 512 | Collections.addAll(list, files); 513 | } 514 | return list; 515 | } 516 | 517 | /** 518 | * 获取目录下所有文件包括子目录 519 | * 520 | * @param dirPath 目录路径 521 | * @return 文件链表 522 | */ 523 | public static List listFilesInDir(String dirPath) { 524 | return listFilesInDir(getFileByPath(dirPath)); 525 | } 526 | 527 | /** 528 | * 获取目录下所有文件包括子目录 529 | * 530 | * @param dir 目录 531 | * @return 文件链表 532 | */ 533 | public static List listFilesInDir(File dir) { 534 | if (!isDir(dir)) return null; 535 | List list = new ArrayList<>(); 536 | File[] files = dir.listFiles(); 537 | if (files != null && files.length != 0) { 538 | for (File file : files) { 539 | list.add(file); 540 | if (file.isDirectory()) { 541 | list.addAll(listFilesInDir(file)); 542 | } 543 | } 544 | } 545 | return list; 546 | } 547 | 548 | /** 549 | * 获取目录下所有后缀名为suffix的文件 550 | *

大小写忽略

551 | * 552 | * @param dirPath 目录路径 553 | * @param suffix 后缀名 554 | * @param isRecursive 是否递归进子目录 555 | * @return 文件链表 556 | */ 557 | public static List listFilesInDirWithFilter(String dirPath, String suffix, boolean isRecursive) { 558 | return listFilesInDirWithFilter(getFileByPath(dirPath), suffix, isRecursive); 559 | } 560 | 561 | /** 562 | * 获取目录下所有后缀名为suffix的文件 563 | *

大小写忽略

564 | * 565 | * @param dir 目录 566 | * @param suffix 后缀名 567 | * @param isRecursive 是否递归进子目录 568 | * @return 文件链表 569 | */ 570 | public static List listFilesInDirWithFilter(File dir, String suffix, boolean isRecursive) { 571 | if (isRecursive) return listFilesInDirWithFilter(dir, suffix); 572 | if (dir == null || !isDir(dir)) return null; 573 | List list = new ArrayList<>(); 574 | File[] files = dir.listFiles(); 575 | if (files != null && files.length != 0) { 576 | for (File file : files) { 577 | if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) { 578 | list.add(file); 579 | } 580 | } 581 | } 582 | return list; 583 | } 584 | 585 | /** 586 | * 获取目录下所有后缀名为suffix的文件包括子目录 587 | *

大小写忽略

588 | * 589 | * @param dirPath 目录路径 590 | * @param suffix 后缀名 591 | * @return 文件链表 592 | */ 593 | public static List listFilesInDirWithFilter(String dirPath, String suffix) { 594 | return listFilesInDirWithFilter(getFileByPath(dirPath), suffix); 595 | } 596 | 597 | /** 598 | * 获取目录下所有后缀名为suffix的文件包括子目录 599 | *

大小写忽略

600 | * 601 | * @param dir 目录 602 | * @param suffix 后缀名 603 | * @return 文件链表 604 | */ 605 | public static List listFilesInDirWithFilter(File dir, String suffix) { 606 | if (dir == null || !isDir(dir)) return null; 607 | List list = new ArrayList<>(); 608 | File[] files = dir.listFiles(); 609 | if (files != null && files.length != 0) { 610 | for (File file : files) { 611 | if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) { 612 | list.add(file); 613 | } 614 | if (file.isDirectory()) { 615 | list.addAll(listFilesInDirWithFilter(file, suffix)); 616 | } 617 | } 618 | } 619 | return list; 620 | } 621 | 622 | /** 623 | * 获取目录下所有符合filter的文件 624 | * 625 | * @param dirPath 目录路径 626 | * @param filter 过滤器 627 | * @param isRecursive 是否递归进子目录 628 | * @return 文件链表 629 | */ 630 | public static List listFilesInDirWithFilter(String dirPath, FilenameFilter filter, boolean isRecursive) { 631 | return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive); 632 | } 633 | 634 | /** 635 | * 获取目录下所有符合filter的文件 636 | * 637 | * @param dir 目录 638 | * @param filter 过滤器 639 | * @param isRecursive 是否递归进子目录 640 | * @return 文件链表 641 | */ 642 | public static List listFilesInDirWithFilter(File dir, FilenameFilter filter, boolean isRecursive) { 643 | if (isRecursive) return listFilesInDirWithFilter(dir, filter); 644 | if (dir == null || !isDir(dir)) return null; 645 | List list = new ArrayList<>(); 646 | File[] files = dir.listFiles(); 647 | if (files != null && files.length != 0) { 648 | for (File file : files) { 649 | if (filter.accept(file.getParentFile(), file.getName())) { 650 | list.add(file); 651 | } 652 | } 653 | } 654 | return list; 655 | } 656 | 657 | /** 658 | * 获取目录下所有符合filter的文件包括子目录 659 | * 660 | * @param dirPath 目录路径 661 | * @param filter 过滤器 662 | * @return 文件链表 663 | */ 664 | public static List listFilesInDirWithFilter(String dirPath, FilenameFilter filter) { 665 | return listFilesInDirWithFilter(getFileByPath(dirPath), filter); 666 | } 667 | 668 | /** 669 | * 获取目录下所有符合filter的文件包括子目录 670 | * 671 | * @param dir 目录 672 | * @param filter 过滤器 673 | * @return 文件链表 674 | */ 675 | public static List listFilesInDirWithFilter(File dir, FilenameFilter filter) { 676 | if (dir == null || !isDir(dir)) return null; 677 | List list = new ArrayList<>(); 678 | File[] files = dir.listFiles(); 679 | if (files != null && files.length != 0) { 680 | for (File file : files) { 681 | if (filter.accept(file.getParentFile(), file.getName())) { 682 | list.add(file); 683 | } 684 | if (file.isDirectory()) { 685 | list.addAll(listFilesInDirWithFilter(file, filter)); 686 | } 687 | } 688 | } 689 | return list; 690 | } 691 | 692 | /** 693 | * 获取目录下指定文件名的文件包括子目录 694 | *

大小写忽略

695 | * 696 | * @param dirPath 目录路径 697 | * @param fileName 文件名 698 | * @return 文件链表 699 | */ 700 | public static List searchFileInDir(String dirPath, String fileName) { 701 | return searchFileInDir(getFileByPath(dirPath), fileName); 702 | } 703 | 704 | /** 705 | * 获取目录下指定文件名的文件包括子目录 706 | *

大小写忽略

707 | * 708 | * @param dir 目录 709 | * @param fileName 文件名 710 | * @return 文件链表 711 | */ 712 | public static List searchFileInDir(File dir, String fileName) { 713 | if (dir == null || !isDir(dir)) return null; 714 | List list = new ArrayList<>(); 715 | File[] files = dir.listFiles(); 716 | if (files != null && files.length != 0) { 717 | for (File file : files) { 718 | if (file.getName().toUpperCase().equals(fileName.toUpperCase())) { 719 | list.add(file); 720 | } 721 | if (file.isDirectory()) { 722 | list.addAll(searchFileInDir(file, fileName)); 723 | } 724 | } 725 | } 726 | return list; 727 | } 728 | 729 | /** 730 | * 将输入流写入文件 731 | * 732 | * @param filePath 路径 733 | * @param is 输入流 734 | * @param append 是否追加在文件末 735 | * @return {@code true}: 写入成功
{@code false}: 写入失败 736 | */ 737 | public static boolean writeFileFromIS(String filePath, InputStream is, boolean append) { 738 | return writeFileFromIS(getFileByPath(filePath), is, append); 739 | } 740 | 741 | /** 742 | * 将输入流写入文件 743 | * 744 | * @param file 文件 745 | * @param is 输入流 746 | * @param append 是否追加在文件末 747 | * @return {@code true}: 写入成功
{@code false}: 写入失败 748 | */ 749 | public static boolean writeFileFromIS(File file, InputStream is, boolean append) { 750 | if (file == null || is == null) return false; 751 | if (!createOrExistsFile(file)) return false; 752 | OutputStream os = null; 753 | try { 754 | os = new BufferedOutputStream(new FileOutputStream(file, append)); 755 | byte data[] = new byte[1024]; 756 | int len; 757 | while ((len = is.read(data, 0, 1024)) != -1) { 758 | os.write(data, 0, len); 759 | } 760 | return true; 761 | } catch (IOException e) { 762 | e.printStackTrace(); 763 | return false; 764 | } finally { 765 | try { 766 | is.close(); 767 | os.close(); 768 | } catch (IOException e) { 769 | e.printStackTrace(); 770 | } 771 | } 772 | } 773 | 774 | /** 775 | * 将字符串写入文件 776 | * 777 | * @param filePath 文件路径 778 | * @param content 写入内容 779 | * @param append 是否追加在文件末 780 | * @return {@code true}: 写入成功
{@code false}: 写入失败 781 | */ 782 | public static boolean writeFileFromString(String filePath, String content, boolean append) { 783 | return writeFileFromString(getFileByPath(filePath), content, append); 784 | } 785 | 786 | /** 787 | * 将字符串写入文件 788 | * 789 | * @param file 文件 790 | * @param content 写入内容 791 | * @param append 是否追加在文件末 792 | * @return {@code true}: 写入成功
{@code false}: 写入失败 793 | */ 794 | public static boolean writeFileFromString(File file, String content, boolean append) { 795 | if (file == null || content == null) return false; 796 | if (!createOrExistsFile(file)) return false; 797 | BufferedWriter bw = null; 798 | try { 799 | bw = new BufferedWriter(new FileWriter(file, append)); 800 | bw.write(content); 801 | return true; 802 | } catch (IOException e) { 803 | e.printStackTrace(); 804 | return false; 805 | } finally { 806 | try { 807 | bw.close(); 808 | } catch (IOException e) { 809 | e.printStackTrace(); 810 | } 811 | } 812 | } 813 | 814 | /** 815 | * 指定编码按行读取文件到List 816 | * 817 | * @param filePath 文件路径 818 | * @param charsetName 编码格式 819 | * @return 文件行链表 820 | */ 821 | public static List readFile2List(String filePath, String charsetName) { 822 | return readFile2List(getFileByPath(filePath), charsetName); 823 | } 824 | 825 | /** 826 | * 指定编码按行读取文件到List 827 | * 828 | * @param file 文件 829 | * @param charsetName 编码格式 830 | * @return 文件行链表 831 | */ 832 | public static List readFile2List(File file, String charsetName) { 833 | return readFile2List(file, 0, 0x7FFFFFFF, charsetName); 834 | } 835 | 836 | /** 837 | * 指定编码按行读取文件到List 838 | * 839 | * @param filePath 文件路径 840 | * @param st 需要读取的开始行数 841 | * @param end 需要读取的结束行数 842 | * @param charsetName 编码格式 843 | * @return 包含制定行的list 844 | */ 845 | public static List readFile2List(String filePath, int st, int end, String 846 | charsetName) { 847 | return readFile2List(getFileByPath(filePath), st, end, charsetName); 848 | } 849 | 850 | /** 851 | * 指定编码按行读取文件到List 852 | * 853 | * @param file 文件 854 | * @param st 需要读取的开始行数 855 | * @param end 需要读取的结束行数 856 | * @param charsetName 编码格式 857 | * @return 包含从start行到end行的list 858 | */ 859 | public static List readFile2List(File file, int st, int end, String charsetName) { 860 | if (file == null) return null; 861 | if (st > end) return null; 862 | BufferedReader reader = null; 863 | try { 864 | String line; 865 | int curLine = 1; 866 | List list = new ArrayList<>(); 867 | if (TextUtils.isEmpty(charsetName)) { 868 | reader = new BufferedReader(new FileReader(file)); 869 | } else { 870 | reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName)); 871 | } 872 | while ((line = reader.readLine()) != null) { 873 | if (curLine > end) break; 874 | if (st <= curLine && curLine <= end) list.add(line); 875 | ++curLine; 876 | } 877 | return list; 878 | } catch (IOException e) { 879 | e.printStackTrace(); 880 | return null; 881 | } finally { 882 | try { 883 | reader.close(); 884 | } catch (IOException e) { 885 | e.printStackTrace(); 886 | } 887 | } 888 | } 889 | 890 | /** 891 | * 指定编码按行读取文件到字符串中 892 | * 893 | * @param filePath 文件路径 894 | * @param charsetName 编码格式 895 | * @return 字符串 896 | */ 897 | public static String readFile2String(String filePath, String charsetName) { 898 | return readFile2String(getFileByPath(filePath), charsetName); 899 | } 900 | 901 | /** 902 | * 指定编码按行读取文件到字符串中 903 | * 904 | * @param file 文件 905 | * @param charsetName 编码格式 906 | * @return 字符串 907 | */ 908 | public static String readFile2String(File file, String charsetName) { 909 | if (file == null) return null; 910 | BufferedReader reader = null; 911 | try { 912 | StringBuilder sb = new StringBuilder(); 913 | if (TextUtils.isEmpty(charsetName)) { 914 | reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); 915 | } else { 916 | reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName)); 917 | } 918 | String line; 919 | while ((line = reader.readLine()) != null) { 920 | sb.append(line).append("\r\n");// windows系统换行为\r\n,Linux为\n 921 | } 922 | // 要去除最后的换行符 923 | return sb.delete(sb.length() - 2, sb.length()).toString(); 924 | } catch (IOException e) { 925 | e.printStackTrace(); 926 | return null; 927 | } finally { 928 | try { 929 | reader.close(); 930 | } catch (IOException e) { 931 | e.printStackTrace(); 932 | } 933 | } 934 | } 935 | 936 | /** 937 | * 读取文件到字符数组中 938 | * 939 | * @param filePath 文件路径 940 | * @return 字符数组 941 | */ 942 | // public static byte[] readFile2Bytes(String filePath) { 943 | //// return readFile2Bytes(getFileByPath(filePath)); 944 | // return readFile2Bytes(getFileByPath(filePath)); 945 | // } 946 | 947 | /** 948 | * 读取文件到字符数组中 949 | * 950 | * @param file 文件 951 | * @return 字符数组 952 | */ 953 | // public static byte[] readFile2Bytes(File file) { 954 | // if (file == null) return null; 955 | // try { 956 | // return ConvertUtils.inputStream2Bytes(new FileInputStream(file)); 957 | // } catch (FileNotFoundException e) { 958 | // e.printStackTrace(); 959 | // return null; 960 | // } 961 | // } 962 | 963 | /** 964 | * 简单获取文件编码格式 965 | * 966 | * @param filePath 文件路径 967 | * @return 文件编码 968 | */ 969 | public static String getFileCharsetSimple(String filePath) { 970 | return getFileCharsetSimple(getFileByPath(filePath)); 971 | } 972 | 973 | /** 974 | * 简单获取文件编码格式 975 | * 976 | * @param file 文件 977 | * @return 文件编码 978 | */ 979 | public static String getFileCharsetSimple(File file) { 980 | int p = 0; 981 | InputStream is = null; 982 | try { 983 | is = new BufferedInputStream(new FileInputStream(file)); 984 | p = (is.read() << 8) + is.read(); 985 | } catch (IOException e) { 986 | e.printStackTrace(); 987 | } finally { 988 | try { 989 | is.close(); 990 | } catch (IOException e) { 991 | e.printStackTrace(); 992 | } 993 | } 994 | switch (p) { 995 | case 0xefbb: 996 | return "UTF-8"; 997 | case 0xfffe: 998 | return "Unicode"; 999 | case 0xfeff: 1000 | return "UTF-16BE"; 1001 | default: 1002 | return "GBK"; 1003 | } 1004 | } 1005 | 1006 | /** 1007 | * 获取文件行数 1008 | * 1009 | * @param filePath 文件路径 1010 | * @return 文件行数 1011 | */ 1012 | public static int getFileLines(String filePath) { 1013 | return getFileLines(getFileByPath(filePath)); 1014 | } 1015 | 1016 | /** 1017 | * 获取文件行数 1018 | * 1019 | * @param file 文件 1020 | * @return 文件行数 1021 | */ 1022 | public static int getFileLines(File file) { 1023 | int count = 1; 1024 | InputStream is = null; 1025 | try { 1026 | is = new BufferedInputStream(new FileInputStream(file)); 1027 | byte[] buffer = new byte[1024]; 1028 | int readChars; 1029 | while ((readChars = is.read(buffer, 0, 1024)) != -1) { 1030 | for (int i = 0; i < readChars; ++i) { 1031 | if (buffer[i] == '\n') ++count; 1032 | } 1033 | } 1034 | } catch (IOException e) { 1035 | e.printStackTrace(); 1036 | } finally { 1037 | try { 1038 | is.close(); 1039 | } catch (IOException e) { 1040 | e.printStackTrace(); 1041 | } 1042 | } 1043 | return count; 1044 | } 1045 | 1046 | /** 1047 | * 获取目录大小 1048 | * 1049 | * @param dirPath 目录路径 1050 | * @return 文件大小 1051 | */ 1052 | public static String getDirSize(String dirPath) { 1053 | // return getDirSize(getFileByPath(dirPath)); 1054 | return ""; 1055 | } 1056 | 1057 | /** 1058 | * 获取目录大小 1059 | * 1060 | * @param dir 目录 1061 | * @return 文件大小 1062 | */ 1063 | // public static String getDirSize(File dir) { 1064 | // long len = getDirLength(dir); 1065 | // return len == -1 ? "" : ConvertUtils.byte2FitMemorySize(len); 1066 | // } 1067 | 1068 | /** 1069 | * 获取文件大小 1070 | * 1071 | * @param filePath 文件路径 1072 | * @return 文件大小 1073 | */ 1074 | public static String getFileSize(String filePath) { 1075 | return getFileSize(getFileByPath(filePath)); 1076 | } 1077 | 1078 | /** 1079 | * 获取文件大小 1080 | * 1081 | * @param file 文件 1082 | * @return 文件大小 1083 | */ 1084 | public static String getFileSize(File file) { 1085 | long len = getFileLength(file); 1086 | return len == -1 ? "" : "w"; 1087 | // return len == -1 ? "" : ConvertUtils.byte2FitMemorySize(len); 1088 | } 1089 | 1090 | /** 1091 | * 获取目录长度 1092 | * 1093 | * @param dirPath 目录路径 1094 | * @return 文件大小 1095 | */ 1096 | public static long getDirLength(String dirPath) { 1097 | return getDirLength(getFileByPath(dirPath)); 1098 | } 1099 | 1100 | /** 1101 | * 获取目录长度 1102 | * 1103 | * @param dir 目录 1104 | * @return 文件大小 1105 | */ 1106 | public static long getDirLength(File dir) { 1107 | if (!isDir(dir)) return -1; 1108 | long len = 0; 1109 | File[] files = dir.listFiles(); 1110 | if (files != null && files.length != 0) { 1111 | for (File file : files) { 1112 | if (file.isDirectory()) { 1113 | len += getDirLength(file); 1114 | } else { 1115 | len += file.length(); 1116 | } 1117 | } 1118 | } 1119 | return len; 1120 | } 1121 | 1122 | /** 1123 | * 获取文件长度 1124 | * 1125 | * @param filePath 文件路径 1126 | * @return 文件大小 1127 | */ 1128 | public static long getFileLength(String filePath) { 1129 | return getFileLength(getFileByPath(filePath)); 1130 | } 1131 | 1132 | /** 1133 | * 获取文件长度 1134 | * 1135 | * @param file 文件 1136 | * @return 文件大小 1137 | */ 1138 | public static long getFileLength(File file) { 1139 | if (!isFile(file)) return -1; 1140 | return file.length(); 1141 | } 1142 | 1143 | /** 1144 | * 获取文件的MD5校验码 1145 | * 1146 | * @param filePath 文件路径 1147 | * @return 文件的MD5校验码 1148 | */ 1149 | public static String getFileMD5ToString(String filePath) { 1150 | File file = TextUtils.isEmpty(filePath) ? null : new File(filePath); 1151 | return getFileMD5ToString(file); 1152 | } 1153 | 1154 | /** 1155 | * 获取文件的MD5校验码 1156 | * 1157 | * @param filePath 文件路径 1158 | * @return 文件的MD5校验码 1159 | */ 1160 | public static byte[] getFileMD5(String filePath) { 1161 | File file = TextUtils.isEmpty(filePath) ? null : new File(filePath); 1162 | return getFileMD5(file); 1163 | } 1164 | 1165 | /** 1166 | * 获取文件的MD5校验码 1167 | * 1168 | * @param file 文件 1169 | * @return 文件的MD5校验码 1170 | */ 1171 | public static String getFileMD5ToString(File file) { 1172 | // return ConvertUtils.bytes2HexString(getFileMD5(file)); 1173 | return "aa"; 1174 | } 1175 | 1176 | /** 1177 | * 获取文件的MD5校验码 1178 | * 1179 | * @param file 文件 1180 | * @return 文件的MD5校验码 1181 | */ 1182 | public static byte[] getFileMD5(File file) { 1183 | if (file == null) return null; 1184 | DigestInputStream dis = null; 1185 | try { 1186 | FileInputStream fis = new FileInputStream(file); 1187 | MessageDigest md = MessageDigest.getInstance("MD5"); 1188 | dis = new DigestInputStream(fis, md); 1189 | byte[] buffer = new byte[1024 * 256]; 1190 | while (dis.read(buffer) > 0) ; 1191 | md = dis.getMessageDigest(); 1192 | return md.digest(); 1193 | } catch (NoSuchAlgorithmException | IOException e) { 1194 | e.printStackTrace(); 1195 | } finally { 1196 | try { 1197 | dis.close(); 1198 | } catch (IOException e) { 1199 | e.printStackTrace(); 1200 | } 1201 | } 1202 | return null; 1203 | } 1204 | 1205 | /** 1206 | * 获取全路径中的最长目录 1207 | * 1208 | * @param file 文件 1209 | * @return filePath最长目录 1210 | */ 1211 | public static String getDirName(File file) { 1212 | if (file == null) return null; 1213 | return getDirName(file.getPath()); 1214 | } 1215 | 1216 | /** 1217 | * 获取全路径中的最长目录 1218 | * 1219 | * @param filePath 文件路径 1220 | * @return filePath最长目录 1221 | */ 1222 | public static String getDirName(String filePath) { 1223 | if (TextUtils.isEmpty(filePath)) return filePath; 1224 | int lastSep = filePath.lastIndexOf(File.separator); 1225 | return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1); 1226 | } 1227 | 1228 | /** 1229 | * 获取全路径中的文件名 1230 | * 1231 | * @param file 文件 1232 | * @return 文件名 1233 | */ 1234 | public static String getFileName(File file) { 1235 | if (file == null) return null; 1236 | return getFileName(file.getPath()); 1237 | } 1238 | 1239 | /** 1240 | * 获取全路径中的文件名 1241 | * 1242 | * @param filePath 文件路径 1243 | * @return 文件名 1244 | */ 1245 | public static String getFileName(String filePath) { 1246 | if (TextUtils.isEmpty(filePath)) return filePath; 1247 | int lastSep = filePath.lastIndexOf(File.separator); 1248 | return lastSep == -1 ? filePath : filePath.substring(lastSep + 1); 1249 | } 1250 | 1251 | /** 1252 | * 获取全路径中的不带拓展名的文件名 1253 | * 1254 | * @param file 文件 1255 | * @return 不带拓展名的文件名 1256 | */ 1257 | public static String getFileNameNoExtension(File file) { 1258 | if (file == null) return null; 1259 | return getFileNameNoExtension(file.getPath()); 1260 | } 1261 | 1262 | /** 1263 | * 获取全路径中的不带拓展名的文件名 1264 | * 1265 | * @param filePath 文件路径 1266 | * @return 不带拓展名的文件名 1267 | */ 1268 | public static String getFileNameNoExtension(String filePath) { 1269 | if (TextUtils.isEmpty(filePath)) return filePath; 1270 | int lastPoi = filePath.lastIndexOf('.'); 1271 | int lastSep = filePath.lastIndexOf(File.separator); 1272 | if (lastSep == -1) { 1273 | return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi)); 1274 | } 1275 | if (lastPoi == -1 || lastSep > lastPoi) { 1276 | return filePath.substring(lastSep + 1); 1277 | } 1278 | return filePath.substring(lastSep + 1, lastPoi); 1279 | } 1280 | 1281 | /** 1282 | * 获取全路径中的文件拓展名 1283 | * 1284 | * @param file 文件 1285 | * @return 文件拓展名 1286 | */ 1287 | public static String getFileExtension(File file) { 1288 | if (file == null) return null; 1289 | return getFileExtension(file.getPath()); 1290 | } 1291 | 1292 | /** 1293 | * 获取全路径中的文件拓展名 1294 | * 1295 | * @param filePath 文件路径 1296 | * @return 文件拓展名 1297 | */ 1298 | public static String getFileExtension(String filePath) { 1299 | if (TextUtils.isEmpty(filePath)) return filePath; 1300 | int lastPoi = filePath.lastIndexOf('.'); 1301 | int lastSep = filePath.lastIndexOf(File.separator); 1302 | if (lastPoi == -1 || lastSep >= lastPoi) return ""; 1303 | return filePath.substring(lastPoi + 1); 1304 | } 1305 | } -------------------------------------------------------------------------------- /app/src/main/java/com/accvmedia/mysocket/util/WifiUtils.java: -------------------------------------------------------------------------------- 1 | package com.accvmedia.mysocket.util; 2 | 3 | import android.content.Context; 4 | import android.net.DhcpInfo; 5 | import android.net.wifi.ScanResult; 6 | import android.net.wifi.WifiConfiguration; 7 | import android.net.wifi.WifiInfo; 8 | import android.net.wifi.WifiManager; 9 | import android.util.Log; 10 | 11 | import java.io.BufferedReader; 12 | import java.io.InputStreamReader; 13 | import java.lang.reflect.Method; 14 | import java.net.InetAddress; 15 | import java.net.UnknownHostException; 16 | import java.util.List; 17 | import java.util.regex.Matcher; 18 | import java.util.regex.Pattern; 19 | 20 | /** 21 | * Created by dempseyZheng on 2016/12/23 22 | */ 23 | 24 | public class WifiUtils { 25 | public static final int WIFICIPHER_NOPASS = 1; 26 | public static final int WIFICIPHER_WEP = 2; 27 | public static final int WIFICIPHER_WPA = 3; 28 | private static final String TAG = "WifiUtils"; 29 | // 定义WifiManager对象 30 | private WifiManager mWifiManager; 31 | // 定义WifiInfo对象 32 | private WifiInfo mWifiInfo; 33 | // 扫描出的网络连接列表 34 | private List mWifiList; 35 | // 网络连接列表 36 | private List mWifiConfiguration; 37 | // 定义一个WifiLock 38 | WifiManager.WifiLock mWifiLock; 39 | private static WifiUtils wifiUtils = null; 40 | 41 | static { 42 | wifiUtils = new WifiUtils(); 43 | } 44 | 45 | public static WifiUtils getInstance() { 46 | return wifiUtils; 47 | 48 | } 49 | 50 | // 构造器 51 | public void init(Context context) { 52 | // 取得WifiManager对象 53 | mWifiManager = (WifiManager) context 54 | .getSystemService(Context.WIFI_SERVICE); 55 | // 取得WifiInfo对象 56 | mWifiInfo = mWifiManager.getConnectionInfo(); 57 | } 58 | 59 | private WifiUtils() { 60 | } 61 | 62 | 63 | // 打开WIFI 64 | public void openWifi() { 65 | if (!mWifiManager.isWifiEnabled()) { 66 | mWifiManager.setWifiEnabled(true); 67 | } 68 | } 69 | 70 | // 断开当前网络 71 | public void disconnectWifi() { 72 | if (!mWifiManager.isWifiEnabled()) { 73 | mWifiManager.disconnect(); 74 | } 75 | } 76 | 77 | // 关闭WIFI 78 | public void closeWifi() { 79 | if (mWifiManager.isWifiEnabled()) { 80 | mWifiManager.setWifiEnabled(false); 81 | } 82 | } 83 | 84 | // 检查当前WIFI状态 85 | public int checkState() { 86 | return mWifiManager.getWifiState(); 87 | } 88 | 89 | // 锁定WifiLock 90 | public void acquireWifiLock() { 91 | mWifiLock.acquire(); 92 | } 93 | 94 | // 解锁WifiLock 95 | public void releaseWifiLock() { 96 | // 判断时候锁定 97 | if (mWifiLock.isHeld()) { 98 | mWifiLock.acquire(); 99 | } 100 | } 101 | 102 | // 创建一个WifiLock 103 | public void creatWifiLock() { 104 | mWifiLock = mWifiManager.createWifiLock("Test"); 105 | } 106 | 107 | // 得到配置好的网络 108 | public List getConfiguration() { 109 | return mWifiConfiguration; 110 | } 111 | 112 | // 指定配置好的网络进行连接 113 | public void connectConfiguration(int index) { 114 | // 索引大于配置好的网络索引返回 115 | if (index > mWifiConfiguration.size()) { 116 | return; 117 | } 118 | // 连接配置好的指定ID的网络 119 | mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, 120 | true); 121 | } 122 | 123 | public void startScan() { 124 | mWifiManager.startScan(); 125 | // 得到扫描结果 126 | mWifiList = mWifiManager.getScanResults(); 127 | // 得到配置好的网络连接 128 | mWifiConfiguration = mWifiManager.getConfiguredNetworks(); 129 | } 130 | 131 | // 得到网络列表 132 | public List getWifiList() { 133 | return mWifiList; 134 | } 135 | 136 | // 查看扫描结果 137 | public StringBuilder lookUpScan() { 138 | StringBuilder stringBuilder = new StringBuilder(); 139 | for (int i = 0; i < mWifiList.size(); i++) { 140 | stringBuilder.append("Index_" + Integer.valueOf(i + 1) 141 | .toString() 142 | + ":"); 143 | // 将ScanResult信息转换成一个字符串包 144 | // 其中把包括:BSSID、SSID、capabilities、frequency、level 145 | stringBuilder.append((mWifiList.get(i)).toString()); 146 | stringBuilder.append("/n"); 147 | } 148 | return stringBuilder; 149 | } 150 | 151 | // 得到MAC地址 152 | public String getMacAddress() { 153 | if (mWifiManager!=null) 154 | mWifiInfo = mWifiManager.getConnectionInfo(); 155 | return (mWifiInfo == null) 156 | ? "NULL" 157 | : mWifiInfo.getMacAddress(); 158 | } 159 | 160 | // 得到接入点的BSSID 161 | public String getBSSID() { 162 | return (mWifiInfo == null) 163 | ? "NULL" 164 | : mWifiInfo.getBSSID(); 165 | } 166 | 167 | // 得到IP地址 168 | public int getIPAddress() { 169 | if (mWifiManager!=null) 170 | mWifiInfo = mWifiManager.getConnectionInfo(); 171 | return (mWifiInfo == null) 172 | ? 0 173 | : mWifiInfo.getIpAddress(); 174 | } 175 | private String intToIp(int i) { 176 | 177 | return (i & 0xFF) + "." + 178 | ((i >> 8) & 0xFF) + "." + 179 | ((i >> 16) & 0xFF) + "." + 180 | (i >> 24 & 0xFF); 181 | } 182 | 183 | public String getParsedIp() { 184 | return intToIp(getIPAddress()); 185 | } 186 | // 得到连接的ID 187 | public int getNetworkId() { 188 | return (mWifiInfo == null) 189 | ? 0 190 | : mWifiInfo.getNetworkId(); 191 | } 192 | 193 | // 得到WifiInfo的所有信息包 194 | public String getWifiInfo() { 195 | return (mWifiInfo == null) 196 | ? "NULL" 197 | : mWifiInfo.toString(); 198 | } 199 | 200 | // 添加一个网络并连接 201 | public void addNetwork(WifiConfiguration wcg) { 202 | int wcgID = mWifiManager.addNetwork(wcg); 203 | boolean b = mWifiManager.enableNetwork(wcgID, true); 204 | System.out.println("netId--" + wcgID); 205 | System.out.println("是否成功--" + b); 206 | } 207 | 208 | // 断开指定ID的网络 209 | public void disconnectWifi(int netId) { 210 | mWifiManager.disableNetwork(netId); 211 | mWifiManager.disconnect(); 212 | } 213 | 214 | public WifiConfiguration CreateWifiInfo(String SSID, String Password, 215 | int Type) 216 | { 217 | if (Password.length()<8){ 218 | throw new RuntimeException("password length must not be less than 8"); 219 | } 220 | WifiConfiguration config = new WifiConfiguration(); 221 | config.allowedAuthAlgorithms.clear(); 222 | config.allowedGroupCiphers.clear(); 223 | config.allowedKeyManagement.clear(); 224 | config.allowedPairwiseCiphers.clear(); 225 | config.allowedProtocols.clear(); 226 | // config.SSID = "\"" + SSID + "\""; 227 | config.SSID = SSID ; 228 | 229 | WifiConfiguration tempConfig = this.IsExsits(SSID); 230 | if (tempConfig != null) { 231 | mWifiManager.removeNetwork(tempConfig.networkId); 232 | } 233 | 234 | if (Type == WIFICIPHER_NOPASS) // WIFICIPHER_NOPASS 235 | { 236 | config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 237 | } 238 | if (Type == WIFICIPHER_WEP) // WIFICIPHER_WEP 239 | { 240 | config.hiddenSSID = true; 241 | // config.wepKeys[0] = "\"" + Password + "\""; 242 | config.wepKeys[0] = Password ; 243 | config.allowedAuthAlgorithms 244 | .set(WifiConfiguration.AuthAlgorithm.SHARED); 245 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 246 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 247 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 248 | config.allowedGroupCiphers 249 | .set(WifiConfiguration.GroupCipher.WEP104); 250 | config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 251 | config.wepTxKeyIndex = 0; 252 | } 253 | if (Type == WIFICIPHER_WPA) // WIFICIPHER_WPA 254 | { 255 | // config.preSharedKey = "\"" + Password + "\""; 256 | config.preSharedKey = Password ; 257 | config.hiddenSSID = true; 258 | config.allowedAuthAlgorithms 259 | .set(WifiConfiguration.AuthAlgorithm.OPEN); 260 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 261 | config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 262 | config.allowedPairwiseCiphers 263 | .set(WifiConfiguration.PairwiseCipher.TKIP); 264 | config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 265 | config.allowedPairwiseCiphers 266 | .set(WifiConfiguration.PairwiseCipher.CCMP); 267 | config.status = WifiConfiguration.Status.ENABLED; 268 | } 269 | return config; 270 | } 271 | 272 | private WifiConfiguration IsExsits(String SSID) { 273 | List existingConfigs = mWifiManager 274 | .getConfiguredNetworks(); 275 | if (existingConfigs!=null&&existingConfigs.size()>0) { 276 | for (WifiConfiguration existingConfig : existingConfigs) { 277 | // if (existingConfig.SSID.equals("\"" + SSID + "\"")) { 278 | if (existingConfig.SSID.equals( SSID )) { 279 | return existingConfig; 280 | } 281 | } 282 | } 283 | return null; 284 | } 285 | 286 | private boolean setWifiApEnabled(String SSID,String pwd,boolean enable){ 287 | closeWifi(); 288 | WifiConfiguration apConfig = CreateWifiInfo(SSID, pwd,WIFICIPHER_WPA); 289 | //通过反射调用设置热点 290 | Method method = null; 291 | try { 292 | method = mWifiManager.getClass().getMethod( 293 | "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE); 294 | 295 | Log.e(TAG, "setWifiAp: "+"连接账号:"+apConfig.SSID+",密码是:"+apConfig.preSharedKey);//提示信息接收方要连接的热点账号和密码 296 | 297 | return (Boolean) method.invoke(mWifiManager, apConfig, enable); 298 | } catch (Exception e) { 299 | e.printStackTrace(); 300 | return false; 301 | } 302 | } 303 | 304 | public void modifyWifiAp(String SSID,String pwd){ 305 | setWifiApEnabled(SSID,pwd,false); 306 | setWifiApEnabled(SSID,pwd,true); 307 | 308 | } 309 | 310 | /** 311 | * 获取局域网的广播地址 312 | * @param context 313 | * @return 314 | * @throws UnknownHostException 315 | */ 316 | public InetAddress getBroadcastAddress(Context context) throws UnknownHostException { 317 | DhcpInfo dhcp = mWifiManager.getDhcpInfo(); 318 | if(dhcp==null) { 319 | return InetAddress.getByName("255.255.255.255"); 320 | } 321 | int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; 322 | byte[] quads = new byte[4]; 323 | for (int k = 0; k < 4; k++) 324 | quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); 325 | return InetAddress.getByAddress(quads); 326 | } 327 | 328 | /** 329 | * 获取路由器MAC地址 330 | * @return 返回MAC地址 331 | */ 332 | public static String getRouterMac(String ip){ 333 | String macAddress = ""; 334 | macAddress = getMacInLinux(ip).trim(); 335 | return macAddress; 336 | } 337 | /** 338 | * @param ip 目标ip 339 | * @return Mac Address 340 | * 341 | */ 342 | public static String getMacInLinux(final String ip){ 343 | String result = ""; 344 | String[] cmd = { 345 | "/bin/sh", 346 | "-c", 347 | "ping " + ip + " -c 2 && arp -a" 348 | }; 349 | String cmdResult = callCmd(cmd); 350 | result = filterMacAddress(ip,cmdResult,":"); 351 | 352 | return result; 353 | } 354 | /** 355 | * 356 | * @param ip 目标ip,一般在局域网内 357 | * @param sourceString 命令处理的结果字符串 358 | * @param macSeparator mac分隔符号 359 | * @return mac地址,用上面的分隔符号表示 360 | */ 361 | public static String filterMacAddress(final String ip, final String sourceString,final String macSeparator) { 362 | String result = ""; 363 | String regExp = "((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})"; 364 | Pattern pattern = Pattern.compile(regExp); 365 | Matcher matcher = pattern.matcher(sourceString); 366 | while(matcher.find()){ 367 | result = matcher.group(1); 368 | if(sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) { 369 | break; //如果有多个IP,只匹配本IP对应的Mac. 370 | } 371 | } 372 | 373 | return result; 374 | } 375 | public static String callCmd(String[] cmd) { 376 | String result = ""; 377 | String line = ""; 378 | try { 379 | Process proc = Runtime.getRuntime().exec(cmd); 380 | InputStreamReader is = new InputStreamReader(proc.getInputStream()); 381 | BufferedReader br = new BufferedReader (is); 382 | while ((line = br.readLine ()) != null) { 383 | result += line; 384 | } 385 | } 386 | catch(Exception e) { 387 | e.printStackTrace(); 388 | } 389 | return result; 390 | } 391 | } 392 | 393 | -------------------------------------------------------------------------------- /app/src/main/res/layout/act_new_client.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 15 | 16 | 21 |