Chapter 4. UDP Dongwon Jeong djeong@kunsan.ac.kr http://ist.kunsan.ac.kr/ Dept. of Informatics & Statistics 목차 UDP 1 1
UDP 개념 자바 UDP 프로그램작성 클라이언트와서버모두 DatagramSocket 클래스로생성 상호간통신은 DatagramPacket 클래스를이용하여 packet 단위로전송 UDP Client UDP Server DatagramSocket() DatagramSocket() 데이터 ( 요청 ) send() receive() 클라이언트요청처리 데이터 ( 응답 ) receive() send() close() UDP 2 UDP 개념 (cont.) DatagramSocket 클래스생성자 DatagramSocket() 로컬컴퓨터의사용가능한임의의포트사용 DatagramSocket(int port) 로컬컴퓨터의주어진포트사용 DatagramSocket(int port, InetAddress addr) 주어진주소와포트번호를사용 UDP 3 2
UDP 개념 (cont.) DatagramPacket 클래스 UDP 는 TCP 와는달리 DatagramPacket 클래스를이용하여데이터를상호주고받음 즉, DatagramPacket 클래스를데이터송신과수신을위한용도로사용 TCP 의경우읽기와쓰기를반복 : read(), write() DatagramPacket 클래스생성자 데이터를받을때이용되는생성자와보낼때이용되는생성자로구분 데이터를받을때이용되는생성자 DatagramPacket(byte[] buf, int length) buf 배열에 length 크기의데이터를받기위한객체생성 DatagramPacket(byte[] buf, int offset, int length) buf 배열의 offset 위치부터 length 개의공간에데이터를받기위한객체생성 데이터를보낼때이용되는생성자 DatagramPacket(byte[] buf, int length, InetAddress address, int port) DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) UDP 4 UDP 프로그램작성 : ConsoleDatagramServer import java.net.*; public class ConsoleDatagramServer { public static void main (String args[]){ DatagramSocket socket; byte[] buf = new byte[1024]; DatagramPacket packet; InetAddress address; socket = new DatagramSocket (1248); System.out.println("DatagramSever is ready."); while (true){ packet = new DatagramPacket (buf, buf.length); socket.receive(packet); int len = packet.getlength(); System.out.print(">>" + new String(buf, 0, len)); address = packet.getaddress(); System.out.print(": from [" + address + ":"); int port = packet.getport(); System.out.println(port + "]"); catch (Exception e) { System.out.println(e); UDP 5 3
UDP 프로그램작성 : ConsoleDatagramClient import java.net.*; import java.io.*; public class ConsoleDatagramClient { public static void main (String args[]){ DatagramSocket socket; DatagramPacket packet; InetAddress address; if (args.length == 0) { System.out.println("Usage: java " + "ConsoleDatagramClient <Server address>"); return; address = InetAddress.getByName(args[0]); socket = new DatagramSocket (1248); while (true){ System.out.print("=>"); String msg = reader.readline(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); byte[] buf = msg.getbytes(); packet = new DatagramPacket (buf, buf.length, address, 1248); socket.send(packet); catch (Exception e) { System.out.println(e); UDP 6 UDP 프로그램작성 : 실행결과 UDP 7 4
UDP 프로그램작성 : MessageServer import java.net.*; public class MessageServer { public static void main (String args[]){ DatagramSocket socket; byte[] buf = new byte[1024]; DatagramPacket packet; InetAddress address; int port; String dstring = null; socket = new DatagramSocket (1268); System.out.println("MessageServer is ready."); while (true){ packet = new DatagramPacket (buf, buf.length); socket.receive(packet); int len = packet.getlength(); catch (Exception e) { System.err.println(e); address = packet.getaddress(); port = packet.getport(); System.out.println(">>" + new String (buf, 0, len)); new MessageWindow (new String (buf, 0, len)); UDP 8 UDP 프로그램작성 : MessageClient import java.net.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class MessageClient extends JFrame implements ActionListener { private DatagramSocket socket=null; private DatagramPacket packet; private JTextField servername; private JTextArea input; private JButton send, clear; public MessageClient(){ super ("Message Client"); JPanel top = new JPanel (new BorderLayout()); top.add(new JLabel ("Server Name"), "West"); servername = new JTextField ("localhost"); top.add(servername, "Center"); getcontentpane().add(top, "North"); input = new JTextArea(); getcontentpane().add(new JScrollPane(input), "Center"); JPanel bottom = new JPanel(); send = new JButton ("Transport"); send.addactionlistener(this); clear = new JButton("Cancel"); clear.addactionlistener(this); bottom.add(send); bottom.add(clear); getcontentpane().add(bottom, "South"); setdefaultcloseoperation(exit_on_close); setsize(400, 200); setvisible(true); UDP 9 5
UDP 프로그램작성 : MessageClient (cont.) protected void sendmessage(string server, String msg){ InetAddress address = null; address = InetAddress.getByName(server); socket = new DatagramSocket(); if (socket!= null) { byte[] buf = msg.getbytes(); packet = new DatagramPacket(buf, buf.length, address, 1268); socket.send(packet); catch (Exception e) { System.out.println(e); finally { socket.close(); String s = servername.gettext(); if (s.trim().length() == 0) return; public void actionperformed (ActionEvent e){ Object b = e.getsource(); if (b == send){ sendmessage (s, input.gettext()); input.settext(""); else { input.settext(""); public static void main (String args[]){ new MessageClient(); // End Program UDP 10 UDP 프로그램작성 : MessageWindow import javax.swing.*; public class MessageWindow extends JFrame { JTextArea data; public MessageWindow (String msg){ super ("Message"); data = new JTextArea (msg); data.seteditable (false); getcontentpane().add(new JScrollPane(data), "Center"); setsize (300, 200); setvisible (true); UDP 11 6
UDP 프로그램작성 : 실행결과 UDP 12 Ref., http://www.shinyoungbok.pe.kr/ UDP 13 7