나는 클라이언트에서 서버로 메시지를 보낼 수있는 간단한 TCP 서버 및 TCP 클라이언트 클래스를 구현하고 메시지는 서버 측에서 대문자로 변환됩니다, 하지만 어떻게 서버에서 클라이언트로 파일을 전송하고 클라이언트에서 서버로 파일을 업로드 할 수 있습니까? 다음과 같은 코드가 있습니다.어떻게 파일을 전송하는 자바에서 TCP 서버와 TCP 클라이언트를 구현
TCPClient.java
:
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String args[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n");
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
TCPServer.java
:
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String args[]) throws Exception {
int firsttime = 1;
while (true) {
String clientSentence;
String capitalizedSentence="";
ServerSocket welcomeSocket = new ServerSocket(3248);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
//System.out.println(clientSentence);
if (clientSentence.equals("set")) {
outToClient.writeBytes("connection is ");
System.out.println("running here");
//welcomeSocket.close();
//outToClient.writeBytes(capitalizedSentence);
}
capitalizedSentence = clientSentence.toUpperCase() + "\n";
//if(!clientSentence.equals("quit"))
outToClient.writeBytes(capitalizedSentence+"enter the message or command: ");
System.out.println("passed");
//outToClient.writeBytes("enter the message or command: ");
welcomeSocket.close();
System.out.println("connection terminated");
}
}
}
그래서, TCPServer.java
먼저 실행됩니다 다음 TCPClient.java
실행, 그리고 내가 사용하려고하여 TCPServer.java
에 절은 테스트하는 경우 사용자 입력이 무엇인지, 이제는 실제로 양쪽에서 파일을 전송하는 방법 (다운로드 및 업로드)을 구현하고 싶습니다. 감사합니다.
http://stackoverflow.com/questions/4687615/how-to-achieve-transfer-file-between-client-and- server-using-java-socket –
모든 대답에 추가하여 [readAllBytes (...)] (http://docs.oracle.com/javase/8/docs/)에서 모든 파일의 모든 바이트를 한 번에 읽을 수 있습니다. api/java/nio/file/Files.html # readAllBytes-java.nio.file.Path-) 파일 w에 쓰기 iith [쓰기 (...)] (http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-byte : A-java.nio.file.OpenOption ...-) – thanopi57