마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Java로 TCP byte stream Client만들기 질문입니다 ?

0 추천
안녕하세요 ?

저는 현재 Java 언어로 TCP Bytestream 기반 Client를 만들고 있습니다.

그런데 난관에 봉착했습니다.    서버와 1회만 통신하는 예제들은 많은데 계속해서 연속적으로

서버와 Data를 받는 부분에 대한 정보는 구하기기 힘들더군요.

public void runReceive() {
  try
  {
   toServer = sock.getOutputStream();
   System.out.println(toServer+"=toServer");
   fromServer = sock.getInputStream();
   System.out.println(fromServer+"=fromServer");
   
   byte[] buf = new byte[10240];
   byte[] bufold = new byte[10240];
   byte[] data = new byte[10240];  
   int count;
   int restCount = 0;
   
   
   
   while (true)
   {
    //toServer.write(buf, 0, count);

    count = fromServer.read(buf);
    System.out.println("count="+count);
    
    System.arraycopy(buf, 0, bufold, restCount, count);
    
    restCount = restCount + count;
    
    if(restCount >= 9) {
     byte[] lenbyte = new byte[4];
     lenbyte[0] = bufold[4];
     lenbyte[1] = bufold[5];
     lenbyte[2] = bufold[6];
     lenbyte[3] = bufold[7];
     int length = byteArrayToInt(lenbyte);

     System.out.println("length="+length);
     
     if(restCount >= (9+length)) {
      System.arraycopy(bufold, 9, data, 0, length);
      FuncSwitch(bufold[8],data);
      restCount = restCount - (9+length);     
      
      if(restCount > 1) {
       System.arraycopy(bufold, (9+length), bufold, 0, restCount);
      }
     }
     else {
      
     }
    }
    else {     
     
     
    }
    
    
    
    //System.out.write(buf, 0, count);
   }
   //toServer.close();
//   while ((count = fromServer.read(buf)) != -1)
//    System.out.write(buf, 0, count);
//   System.out.close();
//   System.out.println(sock + ": 연결 종료");
  }
  catch (IOException ex)
  {
   System.out.println("연결 종료 (" + ex + ")");
  }
/*  finally
  {
   try
   {
    if (sock != null)
     sock.close();
   }
   catch (IOException ex)
   {
   }
  }  
 */
  
 }

위 소스는 제가 만든 소스의 일부분입니다.   위 소스는 1회만 서버와 data를 받고 SocketException을 던지고 소켓이

닫아져 버립니다.

    count = fromServer.read(buf); 이 부분이 Exception을 던지는 것 같습니다.  나머지는 제가 원하는 방식의 데이터

교환로직입니다.

아무런 문제가 없는동안 계속해서 loop를 돌면서 계속해서 byte stream으로 TCP로 서버로부터 data를 받는

부분을 어떻게 만들어야 하나요 ?

고수님들의 조언을 구합니다.

소켓을 열고 받고 닫고 열고 받고 닫고를 반복해야 하나요 ?

이건 너무 소모적인 작업이 되지 않을까요 ?    말이 안되는 것 같습니다.

제가 Java에 입문한지 얼마안돼 지식이 짧습니다.

많은 조언 부탁드립니다.
천사강아지 (240 포인트) 님이 2013년 7월 23일 질문

1개의 답변

0 추천
Exception이 나오면 로그 찍어 보시면 될 것 같구요..

그리고 접속이 끊기는 것이 꼭 클라이언트만의 문제가 아닐 수 있으니

서버쪽에서 끊는 것은 아닌지 확인해 보세요.

채팅 소스만 찾아봐도 무지 많이 나올 것입니다. 검색에 힘쓰세요.
Godwish (2,460 포인트) 님이 2013년 7월 24일 답변
...