본문 바로가기
Programming Language/Java

TCP/IP Socket java code + Keep-Alive 활성화

by 팡팡마트 2023. 11. 17.
728x90

1. KeepAliveServer.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class KeepAliveServer {
    public static void main(String[] args) {
        try {
            // 서버 소켓 생성
            ServerSocket serverSocket = new ServerSocket(1000);
            
            while (true) {
                // 클라이언트의 연결 대기
                Socket clientSocket = serverSocket.accept();
                
                // Keep-Alive 활성화
                clientSocket.setKeepAlive(true);
                
                // 클라이언트로부터 메시지 수신
                BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String message = reader.readLine();
                
                // 수신한 메시지 출력
                System.out.println("Received message from client: " + message);
                
                // 소켓 및 리더 닫기 비활성화
                #reader.close();
                #clientSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

2. KeepAliveClient.java

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class KeepAliveClient {
    public static void main(String[] args) {
        try {
            // 서버에 연결
            Socket socket = new Socket("[서버ip]", 1000);
            
            // Keep-Alive 활성화
            socket.setKeepAlive(true);
            
            // 서버로 메시지 전송
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream, true);
            writer.println("Hello, Server!");
            
            // 소켓, 출력 스트림, 작가 닫기
            writer.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

서버에서 keepalive 확인

# netstat -napo | grep keepalive

**이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

728x90

'Programming Language > Java' 카테고리의 다른 글

Spring boot start  (0) 2023.12.15
TCP/IP Socket java code  (1) 2023.11.17