Java 7일차 UDPServer, UDPClient 테스트

UDPServerTest.java

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServerTest
{
public static final int port = 9000;
public static void main(String[] args)
{
try
{
DatagramSocket ds = new DatagramSocket(9000);
byte[] buf = new byte[256];
DatagramPacket dp = new DatagramPacket(buf, buf.length);

while(true)
{
ds.receive(dp);

byte bmsg[] = dp.getData();
String msg = new String(bmsg, 0 , dp.getLength());
System.out.println(dp.getAddress()+" : "+msg);
}
}

catch(Exception e)
{
e.printStackTrace();
}
}
}

UDPClientTest.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClientTest
{
public static final int port = 9000;
public static void main(String[] args)
{
String host = "localhost";

try
{
InetAddress inet = InetAddress.getByName(host);

BufferedReader key = new BufferedReader(new InputStreamReader(System.in));

String msg = "";
System.out.println("보낼 내용 입력");

DatagramPacket dp = null;
DatagramSocket ds = new DatagramSocket();

while((msg=key.readLine()) != null)
{
if(msg.equalsIgnoreCase(""))
break;

byte[] data = msg.getBytes();

dp = new DatagramPacket(data, data.length, inet, port);
ds.send(dp);
System.out.println("보낼 내용 입력");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}


댓글 없음: