자바 네트워크
TCP/IP
IP : 전세계의 모든 컴퓨터는 IP 프로토콜에 의해 유일 주소를 부여 받는다.
클라이언트 소켓과 서버 소켓 (Client socket & Sercer socket)
서버 소켓 생성 방법
ServerSocket serverSocket = new ServerSocket (9000); // 서버소켓을 생성. 생성자 파라미터로 포트번호 9000을 넘겨줌
serverSocket.accept(); // Cilent socket의 연결 요청이 들어오면 접속을 받아들이고 socket을 리턴
클라이언트 소켓 생성 방법
Socket socket = new Socket("127,0,0,1", 9000); // 서버 IP와 서버프로그램이 열어놓은 포트번호
예제1. TCP/IP로 통신하는 클라이언트/서버 프로그램
1) 서버 프로그램 클래스
package 네트워크;
import java.io.*;
import java.net.*;
public class ServerExample1 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(9000); // 서버소켓 생성
socket = serverSocket.accept(); // 연결요청 기다려 소켓 생성
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte arr[] = new byte[100]; // 최대 100바이트만 받도록
in.read(arr);
System.out.println("server: " + new String(arr)); // 수신된 데이터 출력
String str = "Hello Client"; // 데이터 송신
out.write(str.getBytes());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
finally {
try {
socket.close(); // 소켓닫기
serverSocket.close(); // 서버소켓닫기
}
catch(Exception e) {
}
}
}
}
---------------------------------------------------------------------
2) 클라이언트 프로그램 클래스
package 네트워크;
import java.io.*;
import java.net.*;
public class ClientExample1 {
public static void main(String[] args) {
Socket socket = null; // 클라이언트 소켓 생성
try {
socket = new Socket("localhost", 9000); // localhost는 내컴퓨터IP
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
String str = "Hello, Server";
out.write(str.getBytes());
byte arr[] = new byte[100];
in.read(arr);
System.out.println("client: " + new String(str));
}
catch(Exception e) {
System.out.println(e.getMessage());
}
finally {
try {
socket.close();
}
catch(Exception e) {
}
}
}
}
---------------------------------------------------------------------
3) 결과
예제2. 멀티스레드로 송신과 수신을 동시에 하는 1:1 채팅 프로그램 (p796 참조)
1) 클라이언트 프로그램 클래스
package 네트워크;
import java.net.*;
class ClientExample3 { // 1:1 채팅 프로그램 클라이언트 클래스
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 9001);
Thread thread1 = new SenderThread(socket); // 송신 스레드 생성
Thread thread2 = new ReceiverThread(socket); // 수신 스레드 생성
thread1.start();
thread2.start();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
2) 클라이언트의 메시지 송신 스레드 클래스
package 네트워크;
import java.io.*;
import java.net.*;
class SenderThread extends Thread {
Socket socket;
SenderThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in)); // 키보드로 데이터 입력
PrintWriter writer = // PrintWriter는 stream과 같으나 1줄씩 출력함
new PrintWriter(socket.getOutputStream());
while (true) {
String str = reader.readLine(); // readLine은 1줄 단위로 엔터 누를 때까지
if (str.equals("bye")) // 사용자가 bye라고 입력하면 빠져나감
break;
writer.println(str); // 입력된 문자열을 서버로 송신
writer.flush(); // 버퍼가 꽉 차지 않아도 보냄.
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
try {
socket.close();
}
catch (Exception ignored) {
}
}
}
}
3) 클라이언트의 메시지 수신 스레드 클래스
package 네트워크;
import java.io.*;
import java.net.*;
class ReceiverThread extends Thread {
Socket socket;
ReceiverThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
while (true) { // 서버로부터 메시지 수신하여 모니터로 출력
String str = reader.readLine();
if (str == null)
break;
System.out.println("수신>" + str);
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
4) 서버 프로그램 클래스
package 네트워크;
import java.net.*;
class ServerExample3 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(9001);
socket = serverSocket.accept();
Thread thread1 = new SenderThread(socket);
Thread thread2 = new ReceiverThread(socket);
thread1.start();
thread2.start();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally {
try {
serverSocket.close();
}
catch (Exception ignored) {
}
}
}
}
서버쪽도 3)과 4)와 마찬가지로
5) 서버쪽의 메시지 송신 스레드, 6) 서버쪽의 메시지 수신 스레드 클래스를 만들어줌.
7) 결과
서로 메시지를 주고 받을 수 있는 자바 채팅 프로그램이 완성된다.
예제3. 여러 클라이언트와 동시에 통신하는 채팅 프로그램
(p802 참조)
클라이언트 프로그램으로부터 연결 요청이 올 때마다 스레드가 하나씩 생성되어 서버 프로그램이 동시에 여러 클라이언트 프로그램과 통신하는 방식. 클라이언트의 메시지를 서버의 ArrayList로 받는다.
자세한 것은 생략.
RMI(Remote Method Invocation)
클래스 본체 없이 원격지의 메소드를 호출해주는 개념.
'자바의 기초문법' 카테고리의 다른 글
JDBC 프로그래밍 (0) | 2016.01.07 |
---|---|
HashMap을 이용한 메뉴, 가격 수정 문제 (0) | 2016.01.04 |
GUI 윈도우로 작동하는 덧셈 프로그램 문제 (0) | 2015.12.29 |
GUI 프로그래밍: Swing (0) | 2015.12.29 |
멀티스레드 프로그래밍: Thread, Runnable (0) | 2015.12.28 |