
여러대의 컴퓨터를 통신 회선으로 연결할 것
서비스를 제공하는 프로그램
서비스를 받는 프로그램
네트워크 상에서 컴퓨터를 식별하는 번호
네트워크 어댑터(랜카드) 마다 할당

InetAddress ia = InetAddress.getLocalHost();//방법1 (메개값이 도메인 이름)
InetAddress is = InetAddress.getByNae(String host);
//방법2 (도메인 이름으로 등록돼있는 복수 개의 ip를 가지고 와서 각각 inetadress객체를 만든 다음 배열로)
InetAddress[] iaArr = InetAddress.getAllByName(String host);
String ip = InetAddress.getHostAddress();

보통 도메인에 여러 ip가 연결되어있습니다.
예시
public class InetAddressExample {
public static void main(String[] args) throws Exception {
//로컬 컴퓨터의ip주소 얻어오기
InetAddress local = InetAddress.getLocalHost();
System.out.println("내 컴퓨터 IP주소:" + local.getHostAddress());
//도메인으로 ip주소 검색해서 가져오기
InetAddress[] iaArr = InetAddress.getAllByName("www.naver.com");
for(InetAddress remote : iaArr) {
System.out.println("www.naver.com IP 주소 :" + remote.getHostAddress());
}
}
}
특징 1 : 연결 지향 프로토콜 >> 시간 소요가 됨
특징 2 : 통신 선로 고정 >> 전송 속도 느려질 수도 있음
특징 3 : 데이터를 정확하고 안정적으로 전달
ServerSocket과 Socket

여기서 5001 : 바인딩 할 포트 번호


ServerSoket.close();



public class ServerExample {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket();
//포트와 바인딩하기
//이 경우는 "localhost"서버의 5001번 포트와 바인딩하겠다
serverSocket.bind(new InetSocketAddress("localhost",5001));
while(true) {
System.out.println("[연결 기다림]");
//accept() : 클라이언트의 연결 요청을 수락하는 역할
//클라이언트가 연결요청 해오기 전까지는 대기상태가 됨(블로킹 상태)
//연결 요청이 들어오게 되면 이 포트는 socket객체를 만들고 리턴한다.
//이 socket가지고 클라이언트와 통신한다
Socket socket = serverSocket.accept();
//클라이언트의 ip주소를 받아서 출력해볼까요
InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
System.out.println("연결수락함" + isa.getHostName());
}
} catch (Exception e) {
e.printStackTrace();
}
//ui에서 버튼 눌렀을 때 서버 종료하기 위해
if(!serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class ClientExample {
public static void main(String[] args) {
Socket socket = null;
System.out.println("[연결 요청]");
try {
socket = new Socket();
socket.connect(new InetSocketAddress("localhost",5001));
System.out.println("[연결 성공]");
} catch (IOException e) {
e.printStackTrace();
}
if(!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//입력 스트림 얻기
InpuStream is = socket.getInputSream();
//출력 스트림 얻기
OutputStream os = socket.getOutputStream();


예시
byte[] bytes = null;
String message = null;
//데이터 받기
InputStream is = socket.getInputStream();
bytes = new byte[100];
int readByteCount = is.read(bytes);
message = new String(bytes,0,readByteCount,"UTF-8");
System.out.println("[데이터 받기 성공]"+ message);
//서버가 데이터 보내기
OutputStream os = socket.getOutputStream();
message = "hello client";
bytes = message.getBytes("UTF-8");
os.write(bytes);
os.flush();
System.out.println("[데이터 보내기 성공]");
is.close();
os.close();
socket.close();
//서버로 데이터 보내기
byte[] bytes = null;
String message = null;
OutputStream os = socket.getOutputStream();
message = "Hello server";
bytes = message.getBytes("UTF-8");
os.write(bytes);
os.flush();
System.out.println("[데이터 보내기 성공]");
//서버로부터 데이터 받기
InputStream is = socket.getInputStream();
bytes = new byte[100];
int readByteCount = is.read(bytes);
message = new String(bytes,0,readByteCount,"UTF-8");
System.out.println("[데이터 받기 성공]"+ message);
os.close();
is.close();


스레드의 수는 일정할 것입니다.package java14_net.echoQuiz;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args) {
ServerSocket servSock = null; //리슨 소켓
Socket sock = null; //통신 소켓
BufferedReader in = null; //소켓 입력 스트림
PrintWriter out = null; //소켓 출력 스트림
try {
servSock = new ServerSocket(10005);
System.out.println("+ + + 서버 소켓 생성 + + +");
//반복으로 새로운 클라이언트의 접속 처리
while( true ) {
try {
System.out.println("\n---- 접속 대기중 ----");
System.out.println(" Listen Port : " + servSock.getLocalPort());
System.out.println("---------------------");
sock = servSock.accept(); //Listen
//--- BLOCKED ---
System.out.println("\n 클라이언트 접속!!");
System.out.println("\t>> 클라이언트 IP : " + sock.getInetAddress().getHostAddress());
System.out.println("\t>> 클라이언트 Port : " + sock.getPort());
//--- 데이터 통신 준비 ---
//소켓 입출력 스트림
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(new BufferedOutputStream(sock.getOutputStream()), true);
//--- 데이터 통신 ---
String msg = null;
while( (msg = in.readLine()) != null ) { //입력 데이터가 EOF면 종료
out.println(msg); //에코(Echo) 출력
System.out.println(" 입력받은 메시지>> " + msg); //모니터 출력
}
System.out.println("+ + + 클라이언트의 정상 종료 + + +");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out!=null) out.close(); //소켓 출력스트림 닫기
try {
if(in!=null) in.close(); //소켓 입력스트림 닫기
if(sock!=null) sock.close(); //클라이언트 통신 소켓 닫기
} catch (IOException e) {
e.printStackTrace();
}
}
} //while(true) end - 클라이언트의 접속 및 통신 종료
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(servSock!=null) servSock.close(); //리슨 소켓 닫기
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package java14_net.echoQuiz;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EchoClient {
public static void main(String[] args) {
Socket sock = null; //클라이언트 소켓
BufferedReader in = null; //소켓 입력 스트림
PrintWriter out = null; //소켓 출력 스트림
Scanner sc = new Scanner(System.in); //키보드 입력 스트림
System.out.println("+ + + 클라이언트 실행 + + +");
try {
sock = new Socket("localhost", 10005); //연결 및 통신 준비
//--- 데이터 통신 준비 ---
//소켓 입출력 스트림
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(new BufferedOutputStream(sock.getOutputStream()), true);
//--- 데이터 통신 ---
String msg = null;
while(true) {
System.out.print("\t보낼 데이터 : ");
msg = sc.nextLine();
//통신 중단 명령어
if( "/exit".equals(msg) ) {
break;
}
out.println(msg); //서버로 전송
//Echo(에코) 받은 데이터 출력
System.out.println(">>받은 메시지 : " + in.readLine());
}
System.out.println("+ + + 통신 종료 + + +");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out!=null) out.close(); //소켓 출력스트림 닫기
try {
if(in!=null) in.close(); //소켓 입력스트림 닫기
if(sock!=null) sock.close(); //소켓 닫기
} catch (IOException e) {
e.printStackTrace();
}
}
}
}