TCP实现传送文件增强版 客户端
package day15_18;
import java.io.*;
import java.net.Socket;
public class Demo03_Client {
public static void main(String[] args) throws Exception {
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);
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();
}
}
}
|