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();
}
}
}