여러 대의 컴퓨터를 통신망으로 연결한 것
컴퓨터 사이의 관계에서 서비스를 제공하는 프로그램 또는 컴퓨터
서비스를 제공하는 프로그램으로 클라이언트의 연결 수락하고 요청 내용을 처리 후 응답을 보내는 역할
컴퓨터 사이의 관계에서 서비스를 제공받는 프로그램 또는 컴퓨터
서비스를 받는 프로그램으로 네트워크 데이터를 필요로 하는 모든 어플리케이션이 해당됨
소켓은 프로세스 간 통신에 사용되는 양 끝단이다.
연결 지향형. 데이터를 순차적으로 보내고 데이터를 전송 확인하며 오류 시 재전송한다
빠른 통신을 위한 비연결 방식으로 오류 제어 기능이 없다.
간단하게 Eclipse 두 개를 이용해 소켓 프로그래밍을 구현할 수 있다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
----------------------------------------------------------------------------
int port = 8501;
ServerSocket serverSocket = null;
Socket clientSocket = null;
InputStream is = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
// 예외 처리를 위해 IO 관련 클래스의 변수를 null로 선언
try {
serverSocket = new ServerSocket(port);
// 자바 기본 클래스 사용
System.out.println("기다리는 중..");
// 클라이언트의 소켓을 받을 때까지 기다린다.
clientSocket = serverSocket.accept();
String Ip = clientSocket.getInetAddress().getHostAddress();
System.out.println(Ip+"에서 접속");
// Ip 변수에 클라이언트로 ip주소를 받아온다.
is = clientSocket.getInputStream();
os = clientSocket.getOutputStream();
br = new BufferedReader(new InputStreamReader(is));
pw = new PrintWriter(os);
pw.println("접속 성공");
pw.flush();
// 보조 스트림을 이용하여 클라이언트에서 접속 성공 메세지를 보내준다
String message = br.readLine();
System.out.println(message);
// 보조 스트림을 이용하여 클라이언트가 보낸 메세지를 읽는다
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if(br!= null)br.close();
if(pw!= null)pw.close();
if(clientSocket != null) clientSocket.close();
if(serverSocket != null) serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 예외처리를 하여 사용한 스트림을 닫아준다
}
// 지금까지 서버의 코드
==============================================================
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
---------------------------------------------------------------------------
int port = 8501;
String ip = "127.0.0.1";
// 내부에서 사용할 루프백 ip이다
Socket clientSocket = null;
BufferedReader br = null;
PrintWriter pw = null;
// 마찬가지로 예외처리를 위해 null로 선언
try {
clientSocket = new Socket(ip, port);
// 지정한 ip와 port번호로 접속
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
pw = new PrintWriter(clientSocket.getOutputStream());
String message = br.readLine();
// 서버에서 보낸 메세지를 받는다
System.out.println(message);
Scanner sc = new Scanner(System.in);
System.out.print("보낼 메세지 입력 : ");
String input = sc.nextLine();
pw.println(input);
pw.flush();
//서버에 메세지를 보낸다.
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if(br != null) br.close();
if(pw != null) pw.close();
if(clientSocket != null)clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}