May 5, 2015

UDP Client Server Pemrograman Jaringan
Afriduarchan3:24 PM 0 komentar

Tulisan kali ini merupakan salah satu bagian dari mata kuliah Pemrograman Jaringan pada penulisan saya sebelumnya yaitu Client Server Menggunakan Java Programming. tulisan ini akan membahas dan memberi contoh UDP client server. berikut adalah isi programnya

Udpserver.java(Server)
package udpserver;
import java.net.*;
import java.io.*;
public class Udpserver {
    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!");
InetAddress remote_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());
}
    }
   
}

Udpclient.java (Client)
package udpclient;
import java.net.*;
import java.io.*;
public class Udpclient {
    public static void main(String[] args) {
        try{
String hostname = "localhost";
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 = new ByteArrayOutputStream();
PrintStream pOut = new PrintStream(stream);
pOut.print ("Apa kabar!");
byte[] barray = stream.toByteArray();
DatagramPacket packet = new DatagramPacket(barray, barray.length );
System.out.println ("Target hostname: " + hostname );
InetAddress remote_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());
}
    }
   

}

dan hasil outputnya seperti pada gambar di bawah ini :
- output udpserver

- output udpclient


In Category : ,
About The Author Afriduarchan Network Engineer, College Student of Informatics engineering
Facebook and Twitter

0 komentar

Post a Comment