/*
通过多线程实现客户端并发上传图片
*/
import java.io.*;
import java.net.*;
class PicThread implements Runnable {
private Socket s;
PicThread(Socket s) {
this.s = s;
}
public void run() {
int count = 1;
String ip = s.getInetAddress().getHostAddress();
try {
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
System.out.println(ip + "....connecting");
File file = new File(ip + ".jpg");
while(file.exists())
file = new File(ip + "(" + (count ++) + ")" + ".jpg");
FileOutputStream fos = new FileOutputStream(file);
byte[] by = new byte[1024];
int num = 0;
while((num = in.read(by)) != -1) {
fos.write(by, 0, num);
}
out.write("上传成功".getBytes());
s.close();
fos.close();
} catch(Exception e) {
throw new RuntimeException(ip + "上传失败");
}
}
}
class PicClient02 {
public static void main(String[] args) throws Exception {
/*
if(args.length != 1) {
System.out.println("...请输入一个正确的 .jpg 文件路径");
return;
}*/
File file = new File(args[0]);
if(! (file.exists() && file.isFile())) {
System.out.println("...请检查该文件是否存在");
return;
}
if(! file.getName().endsWith(".jpg")) {
System.out.println("...只要 .jpg 格式的");
return;
}
if(file.length() > 1024*1024*5) {
System.out.println("...文件过大,没安好心");
return;
}
Socket s = new Socket("172.16.41.154", 10005);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
FileInputStream fis = new FileInputStream(file);
byte[] by = new byte[1024];
int num = 0;
while((num = fis.read(by)) != -1) {
out.write(by, 0, num);
}
s.shutdownOutput();
int count = in.read(by); //接受服务端反馈的信息
String info = new String(by, 0, count); //直接利用上面的数组
System.out.println(info);
s.close();
}
}
class PicServer02 {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10005);
while(true) {
Socket s = ss.accept();
new Thread(new PicThread(s)).start();
}
}
}
TCP--通过多线程实现客户端并发上传图片
最新推荐文章于 2023-10-13 21:16:22 发布