。공부 。

Tcp 통신 Client

kyoe 2007. 9. 22. 15:08

import java.io.*;
import java.net.*;

public class Exam06 {
 public static void main(String[] args){
  InetAddress ia = null;
  Socket soc = null;
  PrintWriter out = null;
 
  try{
   ia = InetAddress.getByName("192.168.1.106");  //InetAddress 를 얻어낸다.
   soc = new Socket(ia,12345);       //소켓생성
   out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())));
  }catch(IOException ioe){
   System.err.println("접속 오류 : " +ioe.toString());
   System.exit(-1);
  }
  out.println("이기호" + "\n");  //서버로 "이기호"라는 문자 전송
  out.flush();     //버퍼를 비워낸다.
  out.close();
 }
}

//=========================================
간단한 클라이언트부분 프로그램
여기서 InetAddress 란 Internet Protocol(IP) address를 표현하기 위한 클래스이다.
InetAddress는 도메인과 Ip에 관련된 메소드들이 많다. 음.. 그것들을 다루기위한 클래스 이니까 당연한건지도..
public String getHostAddress()
public static InetAddress getLocalHost()
public static InetAddress getByName(String host)
public static InetAddress[] getAllByName(String host)
public byte[] getAddress()
이외 에도 여러가지 메소드 들이 있는데 많이 쓰이는 것들만을 골라 봤다.
위의 프로그램에서 out.println("이기호" +\n"); 이라는 부분이 있는데 만약 이렇게만 써주고 밑에 줄에 out.flush();
를 써주지 않으면 문자는 전송되지 않는다 서버쪽에서 in.readLine(); 이부분에서 계속 멈춰있음을 알수있다. out.flush()꼭 써주도록 하자