이미지 및 비디오와 같은 파일을 전송하기 위해 java에서 서버 소켓 개념을 사용했습니다. 하지만 클라이언트 측에서는 파일 이름을 사용자 지정합니다. 원래 파일 이름을 그대로 사용할 수 있습니까?서버 소켓 파일 전송
예를 들어:
전송을위한 서버 측에서 파일이 "abc.txt"인 경우에, 나는 (별도의 이름을 거치지 않고) 클라이언트 측에 반영하기 위해이 같은 이름이 필요합니다. 클라이언트 결국
public class FileServer {
public static void main (String [] args) throws Exception {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
OutputStream os = sock.getOutputStream();
new FileServer().send(os);
sock.close();
}
}
public void send(OutputStream os) throws Exception{
// sendfile
File myFile = new File ("C:\\User\\Documents\\abc.png");
byte [] mybytearray = new byte [(int)myFile.length()+1];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
}
: 서버 측에서
public class FileClient{
public static void main (String [] args) throws Exception {
long start = System.currentTimeMillis();
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");
InputStream is = sock.getInputStream();
// receive file
new FileClient().receiveFile(is);
long end = System.currentTimeMillis();
System.out.println(end-start);
sock.close();
}
public void receiveFile(InputStream is) throws Exception{
int filesize=6022386;
int bytesRead;
int current = 0;
byte [] mybytearray = new byte [filesize];
FileOutputStream fos = new FileOutputStream("def");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
}
}
하지만 그 일은 클라이언트에 파일 배열을 보내는 것입니다. 파일의 이름을 파일의 바이트 배열에 추가 할 수 없습니까? 그렇다면 어떻게하는지 알려주십시오. – Arun
@Arun 물론 가능합니다. 프로토콜을 고안하면됩니다. 어떤 직렬화 방법/프로토콜을 사용하고 있습니까? 질문에 실제로 파일을 보내거나받는 코드 (<15 줄)를 포함하면 큰 도움이됩니다. – phihag
전체 소스 코드로 내 질문을 편집했습니다. 이것은 실제로이 질문에 게시 된 링크에서 가져온 것입니다. 친절하게 도와주세요. 늦은 답변 죄송합니다. – Arun