티스토리 뷰

배움/JAVA

소켓통신 테스트

spaces25 2026. 5. 21. 17:47
반응형

1. 서버 측 코드 (전문 수신 및 처리)

서버는 먼저 헤더(4바이트)를 읽어 앞으로 읽어야 할 바디의 크기를 파악한 뒤, 정확히 그 크기만큼만 바디 데이터를 읽어 처리합니다.

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TelegramServer {
    public static void main(String[] args) {
        int port = 6000;

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("[Server] 전문 수신 서버 가동... (Port: " + port + ")");

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("[Server] 클라이언트 연결됨: " + socket.getInetAddress());

                // 바이트 단위 제어를 위해 DataInputStream/OutputStream 사용
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

                try {
                    // 1. 헤더 읽기 (4바이트 - 바디의 길이)
                    int bodyLength = dis.readInt();
                    System.out.println("[Server] 수신된 헤더(바디 길이): " + bodyLength + " bytes");

                    // 2. 바디 읽기 (헤더에 적힌 길이만큼 byte 배열 생성)
                    byte[] bodyBytes = new byte[bodyLength];
                    dis.readFully(bodyBytes); // 지정한 배열 크기만큼 바이트가 다 찰 때까지 블로킹하며 읽음

                    // 3. 전문 해석 (UTF-8 문자열 변환)
                    String telegram = new String(bodyBytes, StandardCharsets.UTF_8);
                    System.out.println("[Server] 수신된 전문 바디: [" + telegram + "]");

                    // 4. 응답 전문 생성 및 전송 (똑같이 헤더 + 바디 구조로 응답)
                    String responseData = "RES_OK|PROCESSING_SUCCESS";
                    byte[] responseBody = responseData.getBytes(StandardCharsets.UTF_8);

                    dos.writeInt(responseBody.length); // 응답 헤더 (4바이트 정수)
                    dos.write(responseBody);           // 응답 바디
                    dos.flush();
                    System.out.println("[Server] 응답 전문 전송 완료 완료");

                } catch (Exception e) {
                    System.out.println("[Server] 전문 처리 중 오류 발생: " + e.getMessage());
                } finally {
                    socket.close();
                    System.out.println("[Server] 클라이언트 연결 종료\n---------------------------------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. 클라이언트 측 코드 (전문 구조 생성 및 전송)

클라이언트는 전송할 문자열의 byte 길이를 계산해 헤더(int, 4바이트)로 먼저 보내고, 이어서 실제 데이터를 전송합니다.

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TelegramClient {
    public static void main(String[] args) {
        String ip = "127.0.0.1";
        int port = 6000;

        try (Socket socket = new Socket(ip, port)) {
            System.out.println("[Client] 서버 연결 성공");

            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            DataInputStream dis = new DataInputStream(socket.getInputStream());

            // 1. 송신할 전문 데이터 생성 (예: 인터페이스ID|요청시간|데이터)
            String telegramData = "REQ_001|20260521173000|HONG_GILDONG|25";
            byte[] bodyBytes = telegramData.getBytes(StandardCharsets.UTF_8);
            
            // 2. 헤더 + 바디 전송
            // writeInt는 4바이트 정수형태로 데이터를 그대로 밀어넣습니다.
            dos.writeInt(bodyBytes.length); // 헤더 전송 (바디 길이)
            dos.write(bodyBytes);           // 바디 전송
            dos.flush();
            System.out.println("[Client] 전문 전송 완료 (바디 크기: " + bodyBytes.length + " bytes)");

            // 3. 서버로부터 응답 전문 수신
            int resBodyLength = dis.readInt(); // 응답 헤더 읽기
            byte[] resBodyBytes = new byte[resBodyLength];
            dis.readFully(resBodyBytes);       // 응답 바디 읽기

            String response = new String(resBodyBytes, StandardCharsets.UTF_8);
            System.out.println("[Client] 서버 응답 전문: [" + response + "]");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/09   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함