//上传图片的客户端
public class UploadClient {
public static void main(String[] args) throws IOException {
System.out.println("客户端." +
"开始发送图片~");
//1.创建对象 和服务端建立链接
Socket socket = new Socket("127.0.0.1", 10023);
//2.创建字节输入流读取本地图片
OutputStream os = socket.getOutputStream();
//图片格式
FileInputStream is = new FileInputStream("路径.png");
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
//3.把客户端写到服务端
os.write(bytes, 0, len);
}
//标记数据传输完成
socket.shutdownOutput();
is.close();
//4.客户端读取服务端返回的数据
InputStream ips = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
System.out.println(str);
socket.close();
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
//上传图片的服务端 支持多个客户端同时上传利用多线程
public class UploadServer {
public static void main(String[] args) throws IOException {
System.out.println("服务端已经启动~~~");
//1.创建服务对象
ServerSocket socket = new ServerSocket(10023);
//2.获取客户端连接
Socket accept = socket.accept();
MyRunnable my = new MyRunnable(accept);
new Thread(my).start();
}
}
//多线程
import java.io.*;
import java.net.Socket;
import java.util.UUID;
public class MyRunnable implements Runnable{
private Socket accept;
public MyRunnable(Socket accept) {
this.accept = accept;
}
@Override
public void run() {
try {
//3.通过客户端获取输入流
InputStream is = accept.getInputStream();
//生成随机图片名
String st1 = UUID.randomUUID().toString();
FileOutputStream os = new FileOutputStream("路径"+st1+".png");
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
os.close();
//4.给客户端一个响应,告诉上传成功
OutputStream ops = accept.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(ops);
BufferedWriter bw = new BufferedWriter(outputStreamWriter);
bw.write("上传成功");
bw.newLine();
bw.flush();//刷新
accept.close();
} catch (IOException e) {
System.out.println("图片上传异常");
}
}
}