본문 바로가기

나는 엔지니어/JAVA

소켓 프로그래밍

클라이언트

1) Socket ( IP , Port  )  생성

2) Input / Output Stream 받는다. (socket으로 부터 생성)

3) write

4) read

5) socket 종료


(sample)

public static void main(String[] args) 

{

// TODO Auto-generated method stub

DataInputStream dis = null;

DataOutputStream dos = null;

Socket sock = null;


try 

{

-----------------  1 -------------------------

sock = new Socket("127.0.0.1",5000); 


---------------- 2 -----------------------------

//1byte stream을 4byte로 확장한 DataStream을 생성

dis = new DataInputStream(sock.getInputStream());

dos = new DataOutputStream(sock.getOutputStream());


int intData = 10;

float floatData = 3.5f;

---------------  3  ---------------------------

dos.writeInt(intData);

dos.writeFloat(floatData);


---------------- 4 -------------------------

intData = dis.readInt();

floatData = dis.readFloat();

dos.writeUTF("TEST");


System.out.println(intData + ":" + floatData);

System.out.println(dis.readUTF());

catch (Exception e) 

{

e.printStackTrace();

// TODO: handle exception

}

finally

{

try

{

----------------  5 -------------------------

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

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

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

}

catch(Exception e)

{}

}

}





서버

1) ServerScoket (port) 생성  ------------> Deamon에 대해서도 알아보자.

2) accept 수행

3) Socket 받아 낸다.

4) Input / Output Stream 을 받는다.

5) read / write 수행

6) Socket 종료

※ 3) , 4) , 5) , 6)은 쓰레드를 활용할 수도 있다.


(sample)

public class ServerTest 

{

public static ServerSocket serv;

public Socket sock;

public static void main(String[] args) 

{

ServerTest server = new ServerTest(5000);

}

public ServerTest(int port)

{

DataInputStream dis = null;

DataOutputStream dos = null;

try 

{

---------------  1 -------------------------------------------

serv = new ServerSocket(port);

while(true)

{

---------------  2  , 3  ------------------------------------------

sock = serv.accept();

---------------- 4 --------------------------------------

dis = new DataInputStream(sock.getInputStream());

dos = new DataOutputStream(sock.getOutputStream());

---------------- 5 ----------------------------------

int intData = dis.readInt();

float floatData = dis.readFloat();

String stringData = dis.readUTF();


dos.writeInt(intData);

dos.writeFloat(floatData);

  dos.writeUTF(stringData + " SERVER");

}

catch (Exception e) 

{

// TODO: handle exception

}

finally

{

try

{

--------------- 6 ---------------------------

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

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

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

}catch(Exception e){}

}

}


}