본문 바로가기

⭐ SpringBoot/🚥 SpringBoot Example

TCP Socket Programming (JAVA) Threeway HandShake

# TCP 소켓 프로그래밍 Threeway HandShake

1. Client - Server 구조 란?

client : 사용자

server : 파일서버, DB서버, EC2 인스턴스, 등등

 보통 서버는 리소스를 전달해주는 역할만을 담당 한다. 
 클라이언트는 보통 리소스를 사용하는 역할이다.

2. Threeway & Four way HandShake 란?

소켓 통신의 기본 개념이라고 볼수 있고 서버 클라이언트 구조에서의 통신 과정? 구조?를 나타낸다.

다른 방식으로는 Four way handshake도 존재한다.

- Threeway HandShake 구조

- Four way handshake 구조

3. JAVA 예제를 활용한 Server Client 구조 구현

자바 17

application.properties 내용은 아래와 같다.

# HTTP 포트
server.port = 8899

- Server 구현 코드

package com.example.tcphttptesthelloworld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

@RestController
@SpringBootApplication
public class TcpHttpTestHelloworldApplication {

    // HTTP HEALTH CHECK
    @RequestMapping("/health")
    String home() {
        return "HTTP PORT TEST 8899";
    }

    public static void main(String[] args) {
        SpringApplication.run(TcpHttpTestHelloworldApplication.class, args);

        // TCP SERVER
        try {
            ServerSocket socket_connection = new ServerSocket(5200);
//            ss.bind (new InetSocketAddress("127.0.0.1", 5200));
            System.out.println("EchoServer is started and waiting for client.....");
            Socket client = socket_connection.accept();
//            socket_connection.wait(15000); // 15초 대기
            // 클라이언트의 연결 요청을 무한정 대기. 연결된 클라이언트의 정보(ip address, mac address, port)
            System.out.println("Client is connected : " + client);

            // 환영메세지 보내기
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
            out.println("Welcom! This is a EchoServer."); // 송신버퍼에 저장 → 원래는 버퍼가 가득차면 보냄.
            out.flush(); // 버퍼에 담기지 않고 바로 나가!. → 송신 버퍼를 운다. 전송 시작됨.
            // → flush되면 버퍼가 비워짐. → 프로그램 종료 → socket해제 → 연결 끊김.
            while (true) {
                String msg = in.readLine(); // 클라이언트로부터 메세지 수신
                System.out.println("From client : " + msg);
                if (msg == null) break;
            }
        } catch (IOException e) {
            e.printStackTrace(); // 어디서 오류가 나는지 체크
//        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

- Client 구현 코드

메인 코드만 구현

package com.example.tcpclient;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

@SpringBootApplication
public class TcpClientApplication {

    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        try {
            Socket socket = new Socket("127.0.0.1", 5200); // AWS EC2 public ip, nlb, alb 등 연결
            System.out.println("Connection is successful!" + socket);
            // 서버의 ip address, port, 자신의 port
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            String msg = in.readLine(); // 수신 한다.
            System.out.println(msg);
            while (true) {
                System.out.print("Your message : ");
                msg = scn.next();
                if (msg.equals("stop")) break;
                out.println(msg); // 엔터가 입력되어야 버퍼가 비워진다.
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

- 끝 -

'⭐ SpringBoot > 🚥 SpringBoot Example' 카테고리의 다른 글

SpringBoot TCP, HTTP 테스트  (0) 2024.02.05