티스토리 뷰

Language/Java

네트워킹

kalza 2018. 9. 5. 16:35

네트워크에 연결되어 있는 대상 사이에 데이터 전송 방법을 배워본다.

네트워크의 데이터 입·출력은 대상 사이에 InputStream, OutputStream을 이용한다.

InputStream과 OutputStream은 네트워크상에서 대화가 오고 갈 때  장치 역할을 해주지만,

교신역할을 해주진 않는다.

현실에서는 멀리 떨어져있는 A , B 두 사람이 서로 대화를 주고 받기 위해서

휴대전화기와 같은 교신 장치를 사용하듯 네트워크상에서는 socket이라는 교신 장치를 사용한다.

자바에서는 이 개념을 Socket 클래스로 구현하여 제공하고 있다.




우선 ServerSocket클래스를 이용하여 네트워크상에 A , B 두사람이 약속된 통신 지점을 만들고

Socket클래스를 통해 접선 할 수 있도록 코드를 작성해보자.


 public static void main(String[] args) {

ServerSocket serverSocket = null;

Socket socket = null;

try {

serverSocket = new ServerSocket(9000);

System.out.println("준비 완료");

socket = serverSocket.accept();

System.out.println("클라이언트 연결~~");

System.out.println("socket: " + socket);

}catch(IOException e) {

e.printStackTrace();

}finally {

try {

if(socket != null)

socket.close();

if(serverSocket != null)

serverSocket.close();

}catch(IOException e) {

e.printStackTrace();

}

}

 }


ServerSocket은 통신 요청이 들어오면 연걸을 허용하는 메서드를 통해 교신 장치인 Socket 객체에 연결을 요청한다.

코드에서 ServerSocket 객체를 생성할때 포트 번호를 갖고 생성자에서 초기화 작업을 진행한다.

접선 포트번호는 9000 이다.

객체가 만들어지면 상대를 맞이할 준비를 하고 있다가 요청에 반응하고 Socket 객체에 연결 할 수 있도록 

socket 참조변수에 accept 메서드를 대입했다.


코드를 실행하고 웹 브라우저를 켜서 주소창에 'localhost:9000' 을 입력하고 접속해보자.


 

이클립스의 콘솔창 결과를 확인해보자.





이제 브라우저를 통해서가 아닌, Socket 클래스를 이용하여 서버에 접속해보자.


 public static void main(String[] args) {

Socket socket = null;

try {

socket = new Socket("localhost", 9000);

System.out.println("서버 접속");

System.out.println("socket: " + socket);

}catch(IOException e) {

e.printStackTrace();

}finally {

try {

if(socket != null)

socket.close();

}catch(IOException e) {

e.printStackTrace();

}

}

 }



Socket 객체 생성시 첫번째 파라미터로 들어가 있는 'localhost'는 네트워크상에서 자신의 컴퓨터를 말하며

IPv4에서의 IP주소로는 127.0.0.1이다. (IPv6에서는 ::1(0:0:0:0:0:0:0:1의 약자)

'localhost' 대신 '127.0.0.1'을 넣어도 무방하다.

이렇게 코드를 작성해서 컴파일을 하면 서버 접속에 성공 할 것이다.

(단, 처음 작성한 코드가 Run중일때)


콘솔창에서 결과를 확인해보자.







이제 A, B 두사람이 InputStream, OutputStream을 이용해서 양방향 통신을 할 수있다.


 public static void main(String[] args) {

ServerSocket serverSocket = null;

Socket socket = null;

InputStream inputStream = null;

DataInputStream dataInputStream = null;

OutputStream outputStream = null;

DataOutputStream dataOutputStream = null;

try {

serverSocket = new ServerSocket(9000);

System.out.println("B 맞이할 준비 완료~~");

socket = serverSocket.accept();

System.out.println("B와 연결됐다!");

System.out.println("socket: " + socket);

inputStream = socket.getInputStream();

dataInputStream = new DataInputStream(inputStream);

outputStream = socket.getOutputStream();

dataOutputStream = new DataOutputStream(outputStream);

while (true) {

String clientMessage = dataInputStream.readUTF();

System.out.println("clientMessage : " + clientMessage);

dataOutputStream.writeUTF("메시지 받음.");

dataOutputStream.flush();

if(clientMessage.equals("STOP")) break;

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if(dataInputStream != null) dataInputStream.close();

if(inputStream != null) inputStream.close();

if(dataOutputStream != null) dataOutputStream.close();

if(outputStream != null) outputStream.close();

if(socket != null) socket.close();

} catch (Exception e) {

e.printStackTrace();

}

}

 }


 public class ClientClass {

public static void main(String[] args) {

Socket socket = null;

OutputStream outputStream = null;

DataOutputStream dataOutputStream = null;

InputStream inputStream = null;

DataInputStream dataInputStream = null;

Scanner scanner = null;

try {

socket = new Socket("localhost", 9000);

System.out.println("서버 연결 완료");

outputStream = socket.getOutputStream();

dataOutputStream = new DataOutputStream(outputStream);

inputStream = socket.getInputStream();

dataInputStream = new DataInputStream(inputStream);

scanner = new Scanner(System.in);

while (true) {

System.out.println("메시지 입력");

String outMessage = scanner.nextLine();

dataOutputStream.writeUTF(outMessage);

dataOutputStream.flush();

String inMessage = dataInputStream.readUTF();

System.out.println("inMessage : " + inMessage);

if(outMessage.equals("STOP")) break;

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if(dataOutputStream != null) dataOutputStream.close();

if(outputStream != null) outputStream.close();

if(dataInputStream != null) dataInputStream.close();

if(inputStream != null) inputStream.close();

if(socket != null) socket.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

 }


'Language > Java' 카테고리의 다른 글

Swing 컴포넌트를 이용한 카페 주문 관리 #2  (2) 2018.09.06
Swing 컴포넌트를 이용한 카페 주문 관리 #1  (0) 2018.09.06
입력과 출력  (0) 2018.09.05
예외처리  (0) 2018.09.04
Collections  (0) 2018.09.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함