UDP
Client-Server UDP Skenario : Server UDP akan menunggu data packet dari client dan selanjutnya menampilkan ke layar konsole.
Server UDP Server UDP berfungsi untuk menunggu data paket yang dikirim oleh client. Pada skenario ini digunakan port 8088.
Kode Program Server UDP Import java.net.*; Import java.io.*; Public class Main { Public static void main (String[] args) { Try{ System.out.println (“UDP Server demo”); System.out.println (“Binding ke port 8088”); DatagramSocket socket = new DatagramSocket(8088); System.out.println (“Bound local port: “ + socket.getLocalPort()); System.out.println (“Menunggu packet datang…”); DatagramPacket packet = new DatagramPacket(new byte[256], 256); socket.receive(packet);
System. out. println (“Packet diterima System.out.println (“Packet diterima!”); InetAddressremote_addr = packet.getAddress(); System.out.println (“IP Address pengirim : “ + remote_addr.getHostAddress()); System.out.println (“Port pengirim: “ + packet.getPort()); ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData()); For (int i=0; i<packet.getLength(); i++) { Int data = bin.read(); If (data == -1) break; Else System.out.print ((char)data); } Socket.close(); Catch(Exception ex) { System.out.println(“Error: “ + ex.getMessage());
Client UDP Client UDP bertugas untuk mengirim data packet ke server UDP. Untuk melakukan hal ini, kita memerlukan informasi hostname dan port dari UDP server.
Kode Program Client UDP Import java.net.*; Import java.io.*; Public class Main { Public static void main (String[] args) { Try { String hostname = “akur”; System.out.println (“UDP Client demo”); System.out.println (“Binding ke local port”); DatagramSocket socket = new DatagramSocket(); System.out.println (“Bound local port : “ + socket.getLocalPort());
ByteArrayOutputStream stream = newByteArrayOutputStream(); PrintStreamOut = new PrintStream(stream); System.out.print (“Apakabar!”); byte[] barray = stream.toByteArray(); DatagramPacket packet = newDatagramPacket (barray, barray.length); System.out.println (“Target hostname: “ + hostname); InetAddressremote_addr = InetAddress.getByName(hostname); System.out.println (“IP Address Hostname: “ + remote_addr.getHostAddress()); Packet.setAddress (remote_addr); Packet.setPort (8088); Socket.send(packet); System.out.println (“Packet telah terkirim!”); } catch(Exception ex){ System.out.println (“Error: “ + ex.getMessage());