📄 runsocketclient.java
字号:
package com.lcj.folder.files;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.File;
public class RunSocketClient {
private SocketClient cs = null;
private String ip = "localhost";// 设置成服务器IP
private int port = 8821;
private String sendMessage = "Windwos";
//设定要读取文件的指定目录
private String basedir = "c:/index/";
public RunSocketClient() {
try {
if (createConnection()) {
sendMessage(basedir);
DataInputStream inputStream = null;
inputStream = cs.getMessageStream();
int filenum = inputStream.readInt();
//inputStream.close();
sendMessage("close");
cs.shutDownConnection();
for (int i = 0; i < filenum; i++) {
// 本地保存路径,文件名会自动从服务器端继承而来。
String savePath = "C:/test/";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len = 0;
if (createConnection()) {
inputStream = cs.getMessageStream();
savePath += inputStream.readUTF();
File saveFile = new File(savePath);
if (!saveFile.getParentFile().exists())
saveFile.getParentFile().mkdir();
if (!saveFile.exists()) {
saveFile.createNewFile();
}
DataOutputStream fileOut = new DataOutputStream(
new BufferedOutputStream(
new BufferedOutputStream(
new FileOutputStream(saveFile))));
len = inputStream.readLong();
System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n");
while (true) {
int readlength = 0;
if (inputStream != null) {
readlength = inputStream.read(buf);
}
passedlen += readlength;
if (readlength == -1) {
break;
}
//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
System.out.println("文件接收了"
+ (passedlen * 100 / len) + "%\n");
fileOut.write(buf, 0, readlength);
}
System.out.println("接收完成,文件存为" + savePath + "\n");
fileOut.close();
cs.shutDownConnection();
buf = null;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean createConnection() {
cs = new SocketClient(ip, port);
try {
cs.CreateConnection();
System.out.print("连接服务器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("连接服务器失败!" + "\n");
return false;
}
}
private void sendMessage(String message) {
if (cs == null) {
System.out.println("SocketClient is null");
return;
}
try {
cs.sendMessage(message);
System.out.println("发送消息成功");
} catch (Exception e) {
System.out.print("发送消息失败!" + "\n");
}
}
private void getMessage() {
}
public static void main(String arg[]) {
new RunSocketClient();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -