보낼 서버의 이름을 가져올 수 있도록 서버를 만들고 싶습니다. 그리고 그 파일을받은 후에 올바른 이름으로 새 위치에 저장할 수 있습니다. 여기 파일의 이름을 보낸 다음 파일 자체를
는 서버 코드 :class TheServer {
public void setUp() throws IOException { // this method is called from Main class.
ServerSocket serverSocket = new ServerSocket(1991);
System.out.println("Server setup and listening...");
Socket connection = serverSocket.accept();
System.out.println("Client connect");
System.out.println("Socket is closed = " + serverSocket.isClosed());
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = rd.readLine();
System.out.println("Recieved: " + str);
rd.close();
InputStream is = connection.getInputStream();
int bufferSize = connection.getReceiveBufferSize();
FileOutputStream fos = new FileOutputStream("C:/" + str);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
connection.close();
serverSocket.close();
}
}
여기 클라이언트 코드 :
public class TheClient {
public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 1991);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(file.getName());
wr.flush();
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
난 내 자신의 몇 가지 테스트를 만들어 내 클라이언트의 이름을 보내는 것 같다 파일 권리,하지만 어떻게 든 서버가 잘못 가져옵니다. 예를 들어 내 클라이언트가 파일 이름이 "test.txt"라고 말하면 내 서버는 "test.txt"와 같은 파일을 얻습니다. -------------------- " 또는 "test.txtPK". 나는 왜 그것이 정상적으로 이름을 얻지 못하는지 이해할 수 없다. 왜 이런 일이 일어나는 지 아는 사람이 있습니까? 아니면 이것을 할 수있는 더 쉬운 방법이 있습니까? 그리고 두 번째 질문은 localhost뿐만 아니라 모든 곳에서 이것을 어떻게 사용할 수 있습니까? 내 IP 주소로 호스트 변경 시도했지만 작동하지 않았다. 감사.
어떻게 할 수 있습니까? –
'wr.write (file.getName()) '다음에'wr.newLine()'을 호출하면됩니다. 스스로, 아마 Apache Commons IO와 같은 라이브러리를 사용할 것입니다. 'java.io' 클래스 위에는 많은 유용한 유틸리티가 있습니다. –
그 덕분에 잘됐다! 감사 –