1. TCP 소켓 통신이란 무엇인가
TCP 소켓 통신이란 TCP(Transmission Control Protocol) 위에서
소켓(Socket) 이라는 통신 종단점을 통해
클라이언트와 서버가 데이터를 주고받는 통신 방식이다.
TCP는 다음과 같은 특징을 가진다.
- 연결 지향(Connection-oriented) 프로토콜이다
- 데이터 전송 순서가 보장된다
- 패킷 손실 시 재전송이 이루어진다
- 신뢰성이 높은 대신 상대적으로 속도가 느리다
이러한 특성 때문에 TCP 소켓 통신은
채팅, 로그인, 게임 서버, 웹 서버 내부 통신 등
정확성과 안정성이 중요한 시스템에서 주로 사용된다.
2. TCP 소켓 통신의 기본 구조
TCP 소켓 통신은 기본적으로 다음 흐름을 따른다.
- 서버는 특정 포트에서 대기한다 (
ServerSocket)
- 클라이언트가 서버로 연결을 시도한다 (
Socket)
- 연결이 수락되면 양쪽에 소켓이 생성된다
- 스트림(InputStream / OutputStream)을 통해 데이터를 주고받는다
- 통신이 종료되면 소켓을 닫는다
이 구조를 기반으로 이후 모든 예제가 확장된다.
3. 단방향 메시지 전송
개념
가장 단순한 형태의 TCP 소켓 통신이다.
클라이언트가 서버로 문자열 메시지 한 줄을 전송하고,
서버는 이를 수신하여 출력한다.
public class MyServer {
public static void main(String[] args) throws IOException {
// 1. 리스너
ServerSocket ss = new ServerSocket(20000);
//2. 소켓
System.out.println("[Server] Waiting");
Socket socket = ss.accept();
System.out.println("[Server] Connected - Create Socket");
// 3. 버퍼
InputStream in = socket.getInputStream();
InputStreamReader ir = new InputStreamReader(in);
BufferedReader br = new BufferedReader(ir);
String msg = br.readLine();
System.out.println("[Server] Client Message : " + msg);
}
}public class MyClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost",20000);
OutputStream out = socket.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(out);
BufferedWriter bw = new BufferedWriter(ow);
bw.write("Hello World");
bw.write("\n");
bw.flush();
}
}핵심 포인트
ServerSocket.accept()는 클라이언트 연결이 올 때까지 블로킹된다
BufferedReader.readLine()은 개행 문자(\n) 기준으로 읽는다
- 이 구조는 Blocking I/O 기반 통신이다
흐름
- Client →
"Hello World\n"전송
- Server → 메시지 수신 후 출력
이 단계에서 TCP 소켓 통신의 최소 단위 구조를 이해할 수 있다.
4. 스트리밍 기반 메시지 전송
개념
단방향 통신을 반복 입력 구조로 확장한 예제다.
클라이언트는 키보드 입력을 지속적으로 서버로 전송하고,
서버는 이를 계속 수신하여 출력한다.
public class MyServer2 {
public static void main(String[] args) {
try {
// 소켓 연결 확인
ServerSocket ss = new ServerSocket(20000);
Socket socket = ss.accept();
// 연결된 소켓에 읽기 기능 설정
InputStream in = socket.getInputStream();
InputStreamReader ir = new InputStreamReader(in);
BufferedReader br = new BufferedReader(ir);
while (true) {
String line = br.readLine(); // 엔터키 까지 읽음
System.out.println("[Server] "+line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}public class MyClient2 {
public static void main(String[] args) {
try {
// localhost = 로컬백주소(자기자신주소) == "127.0.0.1"
// 소켓 생성(로컬 연결)
Socket socket = new Socket("192.168.0.69", 20000);
// 입력
InputStream keyboard = System.in;
InputStreamReader keyReader = new InputStreamReader(keyboard);
BufferedReader keyBuf = new BufferedReader(keyReader);
// 출력
OutputStream out = socket.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(out);
BufferedWriter bw = new BufferedWriter(ow);
while (true) {
String keyboardData = keyBuf.readLine();
bw.write(keyboardData);
bw.write("\n");
bw.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}핵심 포인트
while(true)루프를 통해 지속적인 데이터 송수신이 가능하다
- TCP 연결은 한 번 맺어지면 유지된다
- 데이터는 라인 단위(Line-based Protocol) 로 처리된다
이 단계에서 TCP 통신이 스트림 기반 통신이라는 점이 명확해진다.
5. Request / Response 구조
개념
이 단계부터 통신 구조가 단순 송신이 아닌
요청(Request)과 응답(Response) 형태로 발전한다.
- 클라이언트 → 메시지 전송
- 서버 → 메시지 처리 후
"OK"응답
- 클라이언트 → 서버 응답 수신
public class MyServer3 {
public static void main(String[] args) {
try {
// 소켓 연결 확인
ServerSocket ss = new ServerSocket(20000);
Socket socket = ss.accept();
// 연결된 소켓에 읽기 버퍼 연결
// BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Scanner sc = new Scanner(socket.getInputStream());
// 쓰기용 버퍼
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
while (true) {
String line = sc.nextLine(); // 엔터키 까지 읽음
System.out.println("[Server] "+line);
pw.println("OK");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}public class MyClient3 {
public static void main(String[] args) {
try {
// localhost = 로컬백주소(자기자신주소) == "127.0.0.1"
// 소켓 생성(로컬 연결)
Socket socket = new Socket("127.0.0.1", 20000);
// 키보드 입력
Scanner sc = new Scanner(System.in);
// 소켓에 출력 버퍼 연결
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
// 연결된 소켓에 읽기 버퍼 연결
// BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Scanner socketSc = new Scanner(socket.getInputStream());
while (true) {
String keyboardData = sc.nextLine();
pw.println(keyboardData); // ln이 \n을 자동으로 넣어주고 autoFlush가 된다
String recv = socketSc.nextLine();
System.out.println("서버로 부터 받은 메시지 : " + recv);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}핵심 포인트
- 클라이언트와 서버가 서로 번갈아 가며 읽고 쓴다
- 응답을 기다리는 동안 해당 스레드는 블로킹된다
- 이 구조는 HTTP, 게임 서버 프로토콜의 기본 형태다
이 예제를 통해 통신 프로토콜의 기본 패턴을 이해할 수 있다.
6. JSON 기반 데이터 통신
개념
문자열이 아닌 구조화된 데이터를 주고받는 단계다.
객체를 JSON 문자열로 직렬화하여 전송하고,
서버에서 이를 다시 객체로 복원한다.
사용 기술
Gson라이브러리
- 객체 → JSON (직렬화)
- JSON → 객체 (역직렬화)
public class Person {
private int no;
private String name;
private int age;
private List<String> hobby;
public Person(int no, String name, int age, List<String> hobby) {
this.no = no;
this.name = name;
this.age = age;
this.hobby = hobby;
}
@Override
public String toString() {
return "Person{" +
"no=" + no +
", name='" + name + '\'' +
", age=" + age +
", hobby=" + hobby +
'}';
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getHobby() {
return hobby;
}
public void setHobby(List<String> hobby) {
this.hobby = hobby;
}
}public class MyServer4 {
public static void main(String[] args) {
try {
// 소켓 연결 확인
ServerSocket ss = new ServerSocket(20000);
Socket socket = ss.accept();
// 연결된 소켓에 읽기 버퍼 연결
// BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Scanner sc = new Scanner(socket.getInputStream());
// 쓰기용 버퍼
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
while (true) {
String line = sc.nextLine(); // 엔터키 까지 읽음
Gson gson = new Gson();
Person p = gson.fromJson(line,Person.class);
System.out.println(p.getNo());
System.out.println(p.getName());
System.out.println(p.getAge());
System.out.println(p.getHobby().get(0));
System.out.println(p.getHobby().get(1));
pw.println("OK");
if(p.getAge() > 18)pw.println("성인");
if(p.getAge() <= 18)pw.println("미성년자");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}public class MyClient4 {
public static void main(String[] args) {
try {
// localhost = 로컬백주소(자기자신주소) == "127.0.0.1"
// 소켓 생성(로컬 연결)
Socket socket = new Socket("127.0.0.1", 20000);
// 소켓에 출력 버퍼 연결
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
// 연결된 소켓에 읽기 버퍼 연결
Scanner socketSc = new Scanner(socket.getInputStream());
Person person = new Person(1, "홍길동", 19, Arrays.asList("축구", "농구"));
Gson gson = new Gson();
String json = "";
json = gson.toJson(person);
pw.println(json); // ln이 \n을 자동으로 넣어주고 autoFlush가 된다
String recv = socketSc.nextLine();
System.out.println("서버로 부터 받은 메시지 : " + recv);
} catch (Exception e) {
e.printStackTrace();
}
}
}통신 흐름
- 클라이언트에서
Person객체 생성
- Gson을 이용해 JSON 문자열로 변환
- JSON 문자열을 서버로 전송
- 서버에서 JSON을
Person객체로 복원
- 간단한 비즈니스 로직 수행 (성인/미성년자 판별)
- 서버 응답 전송
핵심 포인트
- TCP는 바이트 스트림만 제공한다
- 데이터 구조는 애플리케이션 레벨에서 정의해야 한다
- JSON은 언어 독립적이고 사람이 읽기 쉬운 포맷이다
이 단계는 실제 서버 통신과 매우 유사한 형태다.
7. 이 코드의 통신 방식 정리
이 실습 코드는 다음과 같이 정의할 수 있다.
- Java TCP Socket 기반 Client–Server 통신
- Blocking I/O 방식
- Line 기반 메시지 프로토콜
- Request / Response 구조
- JSON 직렬화를 통한 객체 데이터 통신
8. 정리
TCP 소켓 통신은 가장 기본적이면서도
모든 네트워크 서버 구조의 출발점이다.
이번 실습을 통해 다음을 이해할 수 있다.
- 소켓 기반 통신의 전체 흐름
- 스트림과 버퍼의 역할
- Blocking I/O의 특성
- 요청과 응답 구조
- 객체 데이터를 문자열(JSON)로 주고받는 방식
이 구조를 기반으로
멀티 스레드 서버, 비동기 I/O(NIO), 실제 서비스 서버 구조로 확장할 수 있다.
Share article