안녕하세요 ?
저는 현재 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에 입문한지 얼마안돼 지식이 짧습니다.
많은 조언 부탁드립니다.