import java.io.*;
import java.net.Socket;
public class MyThread implements Runnable {
public Socket socket;
public MyThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedInputStream bis=null;
FileOutputStream fos = null;
try {
// 创建输出流
fos = new FileOutputStream("d:\\ccc.png");
InputStream inputStream = socket.getInputStream();
// 转换缓冲流
bis = new BufferedInputStream(inputStream);
int len;
byte[] bytes = new byte[1024];
// 写文件
while ((len = bis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("上传成功!");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
===========================================================
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ServerDemo {
public static void main(String[] args) throws IOException {
// 服务端需求:接收客户端发送过来的图片数据。进行存储后,
// 回馈一个“上传成功”字样。支持多的并发用户访问。
ThreadPoolExecutor pool = new ThreadPoolExecutor(
3,//核心线程数量
10, //线程池的总数量
60, //临时线程空闲时间
TimeUnit.SECONDS, //临时线程空闲时间的单位
new ArrayBlockingQueue<>(5),//阻塞队列
Executors.defaultThreadFactory(),//创建线程的方式
new ThreadPoolExecutor.AbortPolicy()//任务拒绝策略
);
// 开启服务器
ServerSocket ss = new ServerSocket(10086);
while (true) {
Socket socket = ss.accept();
MyThread m = new MyThread(socket);
// new Thread(m).start();
pool.submit(m);
}
}
}
=================================================
import java.io.*;
import java.net.Socket;
public class MyThread implements Runnable {
public Socket socket;
public MyThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedInputStream bis=null;
FileOutputStream fos = null;
try {
// 创建输出流
fos = new FileOutputStream("d:\\ccc.png");
InputStream inputStream = socket.getInputStream();
// 转换缓冲流
bis = new BufferedInputStream(inputStream);
int len;
byte[] bytes = new byte[1024];
// 写文件
while ((len = bis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("上传成功!");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端需求:把一个图片文件发送到服务端并读取回馈信息。要求判断文件是否存在及格式是否为jpg并要求文件小于2M。 服务端需求:接收客户端发送过来的图片数据。进行存储后,回馈“上传成功”。支持多用户并发
最新推荐文章于 2024-03-31 19:51:50 发布