2011-08-30 8 views
1

내가 뭘 하려는지 소켓 연결에서 데이터를 읽은 다음 모든 것을 파일에 쓰는 것입니다. 내 독자와 모든 관련 진술은 아래와 같습니다. 왜 그것이 작동하지 않는 아이디어? 이 작업을보다 효율적으로 수행 할 수 있다면 유용 할 것입니다.소켓에서 데이터를 읽고 파일에 쓸 수있는 방법은 무엇입니까?

(내 전체 코드가 성공적으로 소켓에 연결 않음)

편집 : 내 코드를 더 추가되었습니다.

public static void main(String args[]) throws IOException 
{ 

    Date d = new Date(); 
    int port = 5195; 
    String filename = ""; 
    //set up the port the server will listen on 
    ServerSocketChannel ssc = ServerSocketChannel.open(); 
    ssc.socket().bind(new InetSocketAddress(port)); 

    while(true) 
    { 

     System.out.println("Waiting for connection"); 
     SocketChannel sc = ssc.accept(); 
     try 
     { 

      Socket skt = new Socket("localhost", port); 
      BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); 
      FileWriter logfile = new FileWriter(filename); 
      BufferedWriter out = new BufferedWriter(logfile); 
      BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 

      while ((inputLine = stdIn.readLine()) != null) 
      { 
       System.out.println("reading in data"); 
       System.out.println(inputLine); 
       out.write(inputLine); 
       System.out.println("echo: " + in.readLine()); 

      } 

      sc.close(); 

      System.out.println("Connection closed"); 

     } 
+0

무엇이''skt'입니까? 너 자신과 연결되어 있니? 왜? 그리고 왜 당신은'sc'에 입출력을하고 있지 않습니까, 받아 들여진 SocketChannel입니까? – EJP

답변

1

프로그램을 사용하면 소켓에서 읽는 모든 행에 대해 행을 입력해야합니다. 충분한 줄을 입력하고 있습니까?

콘솔에서 읽은 행이 파일에 기록되었으므로 소켓의 행이 파일에 기록 될 것으로 예상 했습니까?

어디 파일 (소켓)

또 다른 방법은 아파치 IOUtils 같은 유틸리티를 사용하는 것입니다 닫는

Socket skt = new Socket("localhost", port); 
IOUtils.copy(skt.getInputStream(), new FileOutputStream(filename)); 
skt.close(); 
+0

그래서이 시도했지만 여전히 데이터가 파일에 기록됩니다. 나는 다음과 같이 포트를 여는 중입니다 : 'ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket(). bind (새 InetSocketAddress (포트)); \t \t 동안 (사실) \t \t { \t \t \t \t \t \t \t에서 System.out.println ("연결 대기 중"); \t \t \t SocketChannel sc = ssc.accept(); ' – Andrew

+0

괜찮아 보입니다. 텔넷을 통해 서버에 연결하는 경우 수신 할 것으로 예상되는 데이터가 있습니까? –

0

나는이 줄에 오타가 있다고 생각 :

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 

"System.in"을 "in"으로 변경하십시오.

FYI, 여기 소켓을 읽는 방법이 나와 있습니다. 나는 독자들에 의해 제공되는 문자열 인코딩을 피하고, 단지 원시 바이트 직진하는 것을 선호 :

byte[] buf = new byte[4096]; 
InputStream in = skt.getInputStream() 
FileOutputStream out = new FileOutputStream(filename); 

int c; 
while ((c = in.read(buf)) >= 0) { 
    if (c > 0) { out.write(buf, 0, c); } 
} 
out.flush(); 
out.close(); 
in.close(); 

오, 귀여운, 그 코드는 피터 Lawrey 본질적으로 IOUtils.copy은() 무엇을 (+1 밝혀 !) :

http://svn.apache.org/viewvc/commons/proper/io/trunk/src/main/java/org/apache/commons/io/CopyUtils.java?view=markup#l193

관련 문제