본문 바로가기

Study/Java

12. 11. 07 네트워크


* 시험 : 이 통신의 순서 쓰기


1. 서버

import java.io.*;

import java.net.*;


public class Server

{

public static void main(String[] args)

{

try

{

int port = Integer.parseInt(args[0]);

ServerSocket ss = new ServerSocket(port);

while (true)

{

Socket s = ss.accept();

OutputStream os = s.getOutputStream();

DataOutputStream dos = new DataOutputStream(os);

for (int i = 1; i <= 10; i++)

{

dos.writeInt(i);

}

s.close();

}

catch (Exception e)

{

System.out.println("Exception : " + e);

}

}


}


클라이언트

import java.*;

import java.net.*;

import java.io.*;


public class console

{

public static void main(String args[]) 

{

try

{

String server = args[0];

int port = Integer.parseInt(args[0]);

Socket c = new Socket(server, port);

InputStream is = c.getInputStream();

DataInputStream dis = new DataInputStream(is);

for (int i = 1; i <= 10; i++)

{

int j = dis.readInt();

System.out.println("서버로부터 받은 데이터 " + j + " 출력");

}

c.close();

catch (Exception e)

{

e.printStackTrace();

}

}

}





2. UDP 서버

import java.*;

import java.net.*;

import java.io.*;


public class console

{

private final static int BUFSIZE = 30;

public static void main(String args[]) 

{

try

{

int port = Integer.parseInt(args[0]);

DatagramSocket ds = new DatagramSocket(port);

while (true)

{

byte buffer[] = new byte[BUFSIZE];

DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

ds.receive(dp);

String str = new String(dp.getData());

System.out.println("수신된 데이터 : " + str);

}

catch (Exception e)

{

e.printStackTrace();

}

}

}


UDP 클라이언트

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

public class Server
{
public static void main(String args[])
{
try
{
int port = Integer.parseInt(args[0]);
ServerSocket ss = new ServerSocket(port);
while (true)
{
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
for (int i = 1; i <= 10; i++)
{
dos.writeInt(i);
}
s.close();
}
catch (Exception e)
{
System.out.println("Exception : " + e);
}
}

}


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

파워자바 PDF  (0) 2012.11.12
에코서버와 에코클라이언트  (0) 2012.11.12
25장 예제  (0) 2012.11.05
26장 과제  (0) 2012.11.05
12. 10. 31  (0) 2012.10.31