Java 파일 전송(TCP,UDP)
UDP:비 접속,전송 불 신,소량의 데이터 전송(패 킷 모드),속도 가 빠 릅 니 다.
TCP
(클 라 이언 트)
package TCP;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;
public class TCP_File_Client {
public static void main(String[] args) {
// Scanner scan = null;
InputStream in = null;
Socket socket = null;
try {
/**
* 1.
* file , File ,
*/
// System.out.println(" :");
// scan = new Scanner(System.in);
// String path = scan.nextLine();
File file = new File("D:\\test.txt");
/**
* 2.
* exists():
* isFile():
*/
if(file.exists() && file.isFile()) {
System.out.println(" ----->");
/**
* 3. ,
* file
*/
in = new FileInputStream(file);
/**
* Socket ( “ ”)。 。
*
* 4.
*/
socket = new Socket();
//InetSocketAddress Inets = new InetSocketAddress("127.0.0.1", 12345);
/**
* 5. TCP
* IP
*/
//socket.connect(new InetSocketAddress("9f9fw7dm.dongtaiyuming.net", 14667));
socket.connect(new InetSocketAddress("127.0.0.1", 8899));
/**
* 6.
* OutputStream getOutputStream()
* 。
*/
OutputStream out = socket.getOutputStream();
/**
* 7.
* ,
* 7.1. , file
* 7.2. file.getName()
* 7.3. file.getName().getBytes()
* 7.4. file.getName().getBytes().length
* 7.5. \r
*/
// [ \r
]
out.write((file.getName().getBytes().length + "\r
").getBytes());
// [ ]
out.write(file.getName().getBytes());
// [ \r
]
out.write((file.length() + "\r
").getBytes());
// [ ]
byte[] data = new byte[1024];
int i = 0;
/*while((i = in.read(data)) != -1) {
out.write(data, 0, i);
}*/
int length = 0;
long progress = 0;
while((length = in.read(data, 0, data.length)) != -1) {
out.write(data, 0, length);
out.flush();
progress += length;
System.out.print("| " + (100*progress/file.length()) + "% |");
}
System.out.println(" ");
}else {
System.out.println(" ~~");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
/**
* Scanner, ,
* ,
*/
// if(scan != null) {
// scan.close();
// }
try {
if(in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//
in = null;
}
try {
if(socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// socket
socket = null;
}
}
System.out.println(" ");
}
}
서버:
package TCP;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCP_File_Server {
public static void main(String[] args) throws Exception {
/**
*
*/
ServerSocket ss = new ServerSocket();
/**
*
*/
ss.bind(new InetSocketAddress(8899));
System.out.println("------ -------");
/**
* socket , socket
*/
/**
* ,
*/
while(true) {
Socket socket = ss.accept();
new Thread(new UpLoad(socket)).start();
}
}
}
class UpLoad implements Runnable{
private Socket socket = null;
public UpLoad(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
OutputStream out = null;
try {
// , socket
InputStream in = socket.getInputStream();
/**
*
* : ( )\r\ \r
\r
* -
*
* line line \r
*/
String line1 = "";
byte[] by1 = new byte[1];
while(!line1.endsWith("\r
")) {
in.read(by1);
String str = new String(by1);
line1 += str;
}
/**
* 1. , \r
* 2.parseInt(): 。
* 3.substring(): , 。
*/
int len1 = Integer.parseInt(line1.substring(0, line1.length() - 2));
/**
* 1.
* 2. ,
* 3.read(data): , data
* data , in , data
*/
byte[] data = new byte[len1];
in.read(data);
String fileName = new String(data);
//
String line2 = "";
byte[] by2 = new byte[1];
while(!line2.endsWith("\r
")) {
in.read(by2);
String str = new String(by2);
line2 += str;
}
int len2 = Integer.parseInt(line2.substring(0, line2.length() - 2));
// ,
String path = "D://copy//" + fileName;
out = new FileOutputStream(path);
//
//
byte[] by3 = new byte[len2];
in.read(by3);
out.write(by3);
System.out.println(" "+socket.getInetAddress().getHostAddress()+" "+path);
} catch (IOException e) {
e.printStackTrace();
}finally {
//
//
try {
if(out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
out = null;
}
// socket
try {
if(socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
socket = null;
}
}
}
}
UDP
(클 라 이언 트)
package upd;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;
public class FileTransferClient extends Socket {
private static final String SERVER_IP = "127.0.0.1"; // IP
private static final int SERVER_PORT = 8899; //
private Socket client;
private FileInputStream fis;
private DataOutputStream dos;
/**
*
*
* @throws Exception
*/
public FileTransferClient() throws Exception {
super(SERVER_IP, SERVER_PORT);
this.client = this;
System.out.println("Cliect[port:" + client.getLocalPort() + "] ");
}
/**
*
* @throws Exception
*/
public void sendFile() throws Exception {
try {
File file = new File("D:\\test.xlsx");
if(file.exists()) {
fis = new FileInputStream(file);
dos = new DataOutputStream(client.getOutputStream());
//
dos.writeUTF(file.getName());
dos.flush();
dos.writeLong(file.length());
dos.flush();
//
System.out.println("======== ========");
byte[] bytes = new byte[1024];
int length = 0;
long progress = 0;
while((length = fis.read(bytes, 0, bytes.length)) != -1) {
dos.write(bytes, 0, length);
dos.flush();
progress += length;
System.out.print("| " + (100*progress/file.length()) + "% |");
}
System.out.println();
System.out.println("======== ========");
dos.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fis != null)
fis.close();
if(dos != null)
dos.close();
client.close();
}
}
/**
*
* @param args
*/
public static void main(String[] args) {
try {
FileTransferClient client = new FileTransferClient(); //
client.sendFile(); //
} catch (Exception e) {
e.printStackTrace();
}
}
}
:
package upd;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.RoundingMode;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
/**
* Server
* :
*
* @author
* @Date 2016 09 01
* @version 1.0
*/
public class FileTransferServer extends ServerSocket {
private static final int SERVER_PORT = 8899; //
private static DecimalFormat df = null;
static {
// ,
df = new DecimalFormat("#0.0");
df.setRoundingMode(RoundingMode.HALF_UP);
df.setMinimumFractionDigits(1);
df.setMaximumFractionDigits(1);
}
public FileTransferServer() throws Exception {
super(SERVER_PORT);
}
/**
*
* @throws Exception
*/
public void load() throws Exception {
System.out.println(" , ......");
while (true) {
// server Socket ,server accept
Socket socket = this.accept();
/**
* , ,
* 。 ,
* ,
*/
// Socket
new Thread(new Task(socket)).start();
}
}
/**
*
*/
class Task implements Runnable {
private Socket socket;
private DataInputStream dis;
private FileOutputStream fos;
public Task(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
dis = new DataInputStream(socket.getInputStream());
//
String fileName = dis.readUTF();
long fileLength = dis.readLong();
File directory = new File("D:\\copy");
if(!directory.exists()) {
directory.mkdir();
}
File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
fos = new FileOutputStream(file);
//
byte[] bytes = new byte[1024];
int length = 0;
while((length = dis.read(bytes, 0, bytes.length)) != -1) {
fos.write(bytes, 0, length);
fos.flush();
}
System.out.println("======== [File Name:" + fileName + "] [Size:" + getFormatFileSize(fileLength) + "] ========");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fos != null)
fos.close();
if(dis != null)
dis.close();
socket.close();
} catch (Exception e) {}
}
}
}
/**
*
* @param length
* @return
*/
private String getFormatFileSize(long length) {
double size = ((double) length) / (1 << 30);
if(size >= 1) {
return df.format(size) + "GB";
}
size = ((double) length) / (1 << 20);
if(size >= 1) {
return df.format(size) + "MB";
}
size = ((double) length) / (1 << 10);
if(size >= 1) {
return df.format(size) + "KB";
}
return length + "B";
}
/**
*
* @param args
*/
public static void main(String[] args) {
try {
FileTransferServer server = new FileTransferServer(); //
server.load();
} catch (Exception e) {
e.printStackTrace();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JAVA 객체 작성 및 제거 방법정적 공장 방법 정적 공장 방법의 장점 를 반환할 수 있습니다. 정적 공장 방법의 단점 류 공유되거나 보호된 구조기를 포함하지 않으면 이불류화할 수 없음 여러 개의 구조기 파라미터를 만났을 때 구축기를 고려해야 한다...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.