텍스트 파일 아이콘패키지 - URLConnection 클래스
Oracle Java 17 ServerSocketDocumentation
Oracle Java 17 Socket Documentation

ServerSocket 클래스는 서버에서 클라이언트의 연결 요청을 기다리고 수락하는 역할을 합니다. 서버는 ServerSocket을 통해 클라이언트가 연결 요청을 보내기를 기다리며, 요청이 오면 이를 처리할 수 있습니다.
ServerSocket 객체를 생성하고, 해당 포트에서 클라이언트의 연결을 대기합니다.Socket 객체를 반환합니다.Socket 클래스는 서버와 클라이언트 간의 실제 데이터 통신을 처리합니다. 클라이언트는 서버의 IP 주소와 포트를 지정해 Socket을 생성하며, 연결이 완료되면 입력 및 출력 스트림을 사용해 데이터를 주고받을 수 있습니다.

package com.exam2;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null; // 서버 소켓 선언
Socket socket = null; // 클라이언트와의 통신을 위한 소켓 선언
try {
// 서버 소켓 생성 - 포트 7777에서 클라이언트 연결을 대기
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
// 클라이언트 연결을 기다림 (연결되면 소켓 객체 반환)
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
} catch (IOException e) {
// 예외 발생 시 에러 메시지 출력
System.out.println("[에러] " + e.getMessage());
} finally {
// 클라이언트 소켓 닫기
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// 클라이언트 소켓 닫기 실패 시 처리
}
}
// 서버 소켓 닫기
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// 서버 소켓 닫기 실패 시 처리
}
}
}
}
}
package com.exam2;
import java.io.IOException;
import java.net.Socket;
public class TCPClientEx01 {
public static void main(String[] args) {
Socket socket = null;
try {
System.out.println("서버와 연결을 시작합니다");
// 서버에 연결 시도 - 로컬 호스트의 포트 7777로 연결
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
} catch (IOException e) {
// 연결 실패 시 에러 메시지 출력
System.out.println("[에러] " + e.getMessage());
} finally {
// 소켓이 열려 있다면 닫기
if (socket != null) { try { socket.close(); } catch (IOException e) {}}
}
}
}
// 서버 코드 (에코 서버)
package com.exam5;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServerEx01 {
public static void main(String[] args) {
// 무한 대기 중인 서버
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null; // 클라이언트로부터 입력받는 스트림
BufferedWriter bw = null; // 클라이언트로 출력하는 스트림
try {
serverSocket = new ServerSocket(7777); // 포트 7777에서 서버 소켓 생성
while (true) { // 클라이언트 연결을 계속 대기
try {
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept(); // 클라이언트 연결 대기
System.out.println("클라이언트가 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8")); // 입력 스트림 설정
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8")); // 출력 스트림 설정
// 클라이언트로부터 받은 메시지를 다시 클라이언트로 전송 (에코)
String message = br.readLine(); // 클라이언트로부터 메시지 읽기
bw.write(message + System.lineSeparator()); // 읽은 메시지를 클라이언트로 전송
bw.flush(); // 스트림 비우기
System.out.println("전송 완료: " + message);
} catch (IOException e) {
System.out.println("[에러] " + e.getMessage());
} finally {
// 자원 해제
if (br != null) try { br.close(); } catch (IOException e) {}
if (bw != null) try { bw.close(); } catch (IOException e) {}
if (socket != null) try { socket.close(); } catch (IOException e) {}
}
}
} catch (IOException e1) {
System.out.println("[에러] " + e1.getMessage());
} finally {
// 서버 소켓 닫기
if (serverSocket != null) try { serverSocket.close(); } catch (IOException e) {}
}
}
}
// 클라이언트 코드 (서버에 메시지 전송 후 에코 메시지 받음)
package com.exam5;
import java.io.*;
import java.net.Socket;
public class TCPClientEx01 {
public static void main(String[] args) {
Socket socket = null;
BufferedWriter bw = null; // 서버로 메시지를 전송하는 스트림
BufferedReader br = null; // 서버로부터 메시지를 받는 스트림
try {
System.out.println("서버와 연결을 시작합니다.");
socket = new Socket("localhost", 7777); // 로컬 호스트의 포트 7777로 연결
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8")); // 출력 스트림 설정
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8")); // 입력 스트림 설정
// 서버로 메시지 전송
bw.write("안녕 소켓" + System.lineSeparator());
bw.flush(); // 스트림 비우기
// 서버로부터 에코 메시지 수신
String response = br.readLine();
System.out.println("[에코메시지] " + response);
} catch (IOException e) {
System.out.println("[에러] " + e.getMessage());
} finally {
// 자원 해제
if (bw != null) { try { bw.close(); } catch (IOException e) {} }
if (br != null) { try { br.close(); } catch (IOException e) {} }
if (socket != null) { try { socket.close(); } catch (IOException e) {} }
}
}
}
``