2011-01-12 5 views
10

나는 클라이언트에서 서버로 메시지를 보낼 수있는 간단한 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에 절은 테스트하는 경우 사용자 입력이 무엇인지, 이제는 실제로 양쪽에서 파일을 전송하는 방법 (다운로드 및 업로드)을 구현하고 싶습니다. 감사합니다.

+0

http://stackoverflow.com/questions/4687615/how-to-achieve-transfer-file-between-client-and- server-using-java-socket –

+0

모든 대답에 추가하여 [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

답변

2

This 링크가 도움이됩니다.

+0

if (clientSentence.equals ("good")) \t {capitalizedSentence = "연결이 설정 됨"; \t //outToClient.writeBytes(capitalizedSentence); \t 다른} \t \t \t \t {capitalizedSentence clientSentence.toUpperCase =() + "\ n을"; \t \t \t \t \t \t } outToClient.writeBytes (capitalizedSentence); welcomeSocket.close(); 서버 코드와 비슷하지만 작동하지 않는 것 같습니다. 도움을 받으실 수 있습니까? – starcaller

+0

현재 어떤 코드를 사용하고 있으며 어떤 예외가 있는지 알려 주셔야합니다. – npinti

+0

질문을 업데이트했습니다. 감사합니다. 감사합니다. – starcaller

1

앞뒤로 파일을 메시지를 보낼뿐만 아니라 전송 지원을 계속하려는 가정 ...

당신은 지금, 당신은 클라이언트에서 서버로 데이터를 전송하는 writeBytes을 사용하는 것처럼.

당신은 파일의 내용처럼, 아무것도 보낼 것을 사용할 수 있습니다 ...

하지만 당신은 그들이 파일이보다는 전송 될 때 알 수 있도록 클라이언트와 서버 사이의 프로토콜을 정의해야합니다 채팅 메시지.

예를 들어 서버에 파일을 보내기 전에 메시지/문자열 "FILECOMING"을 보낼 수 있습니다. 그러면 파일의 바이트를 예상하는 것으로 알 수 있습니다. 마찬가지로 파일의 끝을 표시하는 방법이 필요합니다.

또는 각 메시지 앞에 메시지 유형을 보낼 수 있습니다.

더 나은 응답/솔루션은 별도의 스레드/소켓에서 파일 전송을하는 것입니다. 즉, 채팅 메시지가 전송에 의해 보류되지 않습니다. 파일 전송이 필요할 때마다 새로운 스레드/소켓 연결이 만들어집니다.

~ 크리스

+0

이되면 답안이 쓸모 없게되지 않도록 링크 *의 관련 부분을 답안 *에 포함 시키십시오. – starcaller

+0

명령을 처리하기 위해 별도의 소켓을 사용해야하는 것이 이상적입니다. FTP로 완료하는 방법은 명령 채널과 데이터 채널이 있다는 것입니다. –

4

은 그래서 당신은 파일 이름과 파일 경로를받은 서버 측에서 가정 할 수 있습니다. 이 코드는 당신에게 약간의 아이디어를 줄 것입니다.

서버에

PrintStream out = new PrintStream(socket.getOutputStream(), true); 
FileInputStream requestedfile = new FileInputStream(completeFilePath); 
byte[] buffer = new byte[1]; 
out.println("Content-Length: "+new File(completeFilePath).length()); // for the client to receive file 
while((requestedfile.read(buffer)!=-1)){ 
    out.write(buffer); 
    out.flush();  
    out.close();  
} 
requestedfile.close(); 

CLIENT

DataInputStream in = new DataInputStream(socket.getInputStream()); 
int size = Integer.parseInt(in.readLine().split(": ")[1]); 
byte[] item = new byte[size]; 
for(int i = 0; i < size; i++) 
    item[i] = in.readByte(); 
FileOutputStream requestedfile = new FileOutputStream(new File(fileName)); 
BufferedOutputStream bos = new BufferedOutputStream(requestedfile); 
bos.write(item); 
bos.close(); 
fos.close(); 
0
import java.io.*; 
import java.net.*; 

class TCPClient 
{ 
    public static void main(String argv[]) throws IOException 
    { 
     String sentence; 
     String modifiedSentence; 
     Socket clientSocket = new Socket("*localhost*", *portnum*); // new Socket("192.168.1.100", 80); 
     System.out.println("Enter your ASCII code here"); 
     BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
     sentence = inFromUser.readLine(); 
// System.out.println(sentence); 

      while(!(sentence.isEmpty())) 
      {   
       DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
       outToServer.writeBytes(sentence); 

       BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
       modifiedSentence = inFromServer.readLine(); 

        while(!(modifiedSentence.isEmpty())) 
        {     
         System.out.println("FROM SERVER: " + modifiedSentence); 
         break; 
        } 

       System.out.println("Enter your ASCII code here"); 
       inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
       sentence = inFromUser.readLine(); 
      } 

     System.out.println("socket connection going to be close");  
     clientSocket.close(); 
    } 

}