TCP实现传送文件增强版
客户端
package day15_18;
import java.io.*;
import java.net.Socket;
public class Demo03_Client {
public static void main(String[] args) throws Exception {
//创建客户端socket对象
Socket s = new Socket("127.0.0.1", 10086);
//创建网络输入输出流
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
//接收服务器 和 传给服务器用的字符缓冲流
BufferedReader br=new BufferedReader(new InputStreamReader(is));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
//先传文件名可以判断传的东西 先封装成文件降低耦合性
File file=new File("C:\\Users\\阿云\\Desktop\\壁纸\\Feng201602_4_1920x1080.jpg");
bw.write(file.getName());
bw.newLine();
//这儿必须刷新不刷新没有东西写入
bw.flush();
//读一行会解决数据丢失问题 没有传文件内容
String start = br.readLine();
System.out.println(start);
//获取本地文件 地址可以修改
FileInputStream fis = new FileInputStream(file);
//循环输出
byte[] bys = new byte[1024 * 8];
int len;
while ((len = fis.read(bys)) != -1) {
os.write(bys, 0, len);
}
//这儿不加的话一直服务器会一直读 读是阻塞的方法 这就是结束标记!!!
s.shutdownOutput();
//接收反馈
String result = br.readLine();
System.out.println(result);
//关流
s.close();
fis.close();
}
}
服务端
package day15_18;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo03_Sever {
public static void main(String[] args) throws Exception {
//创建线程池多线程工作
ExecutorService service= Executors.newFixedThreadPool(10);
//服务器端socket对象
ServerSocket ss = new ServerSocket(10086);
while (true) {
//侦听
Socket s = ss.accept();
Demo03_Thread demo03_thread = new Demo03_Thread(s);
service.submit(demo03_thread);
}
}
}
多线程
package day15_18;
import java.io.*;
import java.net.Socket;
import java.util.UUID;
public class Demo03_Thread implements Runnable {
public Socket s;
public Demo03_Thread(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
//通话
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
//回写字符串上传成功 用字符流包一下
BufferedReader br = new BufferedReader(new InputStreamReader(is));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
//先读取第一行 丢失数据原因读一行之后的数据会丢失
String filename = br.readLine();
System.out.println(filename);
//回写上传成功 让接着上传文件内容
bw.write("文件名上传成功");
bw.newLine();
//这儿必须刷新不刷新没有东西写入
bw.flush();
//创建随机的名字 解决重名问题
UUID uuid = UUID.randomUUID();
//输出端
FileOutputStream fos = new FileOutputStream("C:\\Users\\阿云\\Desktop\\" + uuid + "_" + filename);
//循环判断
byte[] bys = new byte[1024 * 8];
int len;
while ((len = is.read(bys)) != -1) {
fos.write(bys, 0, len);
}
//回写
bw.write("上传成功");
bw.newLine();
//这儿必须刷新不刷新没有东西写入
bw.flush();
//关流
s.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}