单线程上传
服务端:
public static void main(String[] args) {
try (
ServerSocket server = new ServerSocket(8000);
Socket socket = server.accept();
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
FileOutputStream out = new FileOutputStream("C:\\Users\\14172\\Pictures\\m66.png")) {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}System.out.println("接收完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
客户端:
public class UdpClient {
public static void main(String[] args) {
try (
Socket socket = new Socket("127.0.0.1", 8000);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
FileInputStream fin = new FileInputStream("C:\\Users\\14172\\Pictures\\m11.png");
BufferedInputStream in = new BufferedInputStream(fin)) {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
System.out.println("上传成功!");
} catch (
ConnectException e) {
System.out.println("服务器未启动!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
查看文件: 可以看到自己的目录下已经出现了C:\Users\14172\Pictures\m66.png
多线程上传
改成多线程的形式:
修改服务端:
public class isStream {
public static void main(String[] args)throws Exception {
ServerSocket server = new ServerSocket(8000);
while (true)
{
Socket socket = server.accept();
new ServerReadThread(socket).start();
}
}
class ServerReadThread extends Thread {
static int number = 0;
private Socket socket;
public ServerReadThread(Socket socket) {
this.socket = socket;
}
@Override
public void run(){
try(
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
FileOutputStream out = new FileOutputStream("C:\\Users\\14172\\socket\\"+number+".png"))
{
number++;
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
System.out.println("接收完成!");
}
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
查看结果:
修改客户端
修改为用户输入图片路径,进行多次上传图片:
public class UdpClient {
public static void main(String[] args) throws IOException {
int num = 0;
Socket socket = new Socket("127.0.0.1", 8000);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in);
while (true) {
num++;
try (
FileInputStream fin = new FileInputStream(scanner.nextLine());
BufferedInputStream in = new BufferedInputStream(fin)) {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
System.out.println("上传成功!");
} catch (ConnectException e) {
System.out.println("服务器未启动!");
} catch (IOException e) {
e.printStackTrace();
}
if(num == 5) break;
}
}
}
查看目录: 发现一个小问题:已经存在的一样的命名的图片不会覆盖 然后有的图片传过去之后格式会损坏,貌似是jpg转为png命名的时候
|