클라이언트 코드

package com.blog.naver.fiesta77.client;

import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class ClientTest {
  private static final String CONN_HOST = "www.host.com";
  private static final int    CONN_PORT = 12345;
  public static void main(String[] args) {
    Socket socket = null;
    try {
      socket = new Socket(CONN_HOST, CONN_PORT);
      DataInputStrean in = new DataInputStream(socket.getInputStream());
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());

      int message = in.readInt();
      System.out.printf("recv message is %d\n", message);
      message *= 10;
      out.writeInt(message);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (socket != null) try { socket.close(); } try (IOException e) {}
    }
  }
}


코드 분석


클라이언트 소켓 프로그래밍은 서버 소켓 프로그래밍과 별반 차이가 없다.
자바의 net 패키지가 워낙에 쉽게 소켓 프로그래밍을 할 수 있도록 만들어서인데
ServerSocket 대신 Socket 객체를 생성할 때 접속할 호스트와 포트만 넘겨주면 끝이다.
그 이후는 서버 프로그래밍과 마찬가지로 InputStream과 OutputStream으로 데이터를 넘겨주면 끝이다.
(Stream은 바이너리 형식이므로 만약 String을 사용할 예정이라면 Reader를 사용하면 된다.)

+ Recent posts