Network Programming UDP Socket (NPUS)

Instructional Objectives

After participating in this practicum, students are expected to be able to:

  1. Understanding UDP Sockets.
  2. Implementing UDP sockets on server and client.

1. UDP Socket

User Datagram Protocol (UDP), is one of the TCP/IP transport layer protocols that supports unreliable, connectionless communication between hosts on a TCP/IP network. UDP has the following characteristics:

  1. Connectionless: UDP messages will be sent without having to negotiate a connection between the two hosts that want to exchange information.
  2. Unreliable: UDP messages are delivered as datagrams without sequence numbers or acknowledgments.
    Application layer protocols running on top of UDP must recover from messages lost during transmission.
    Typically, application layer protocols running on top of UDP implement their own reliability services, or deliver messages periodically or at a predefined time.
  3. UDP provides a mechanism for sending messages to a specific application layer protocol or process within a host on a network that uses TCP/IP.
    The UDP header contains the Source Process Identification and Destination Process Identification fields.
  4. UDP provides a 16-bit checksum calculation of the entire UDP message.

2. Server Program

import java.net.*;
import java.io.*;

class ServerDatagram {
    public static DatagramSocket ds;
    public static int clientport=800,serverport=900;
 
    public static void main (String args[]) throws Exception {
    byte buffer[]= new byte[1024];
    ds= new DatagramSocket (serverport);
 
    BufferedReader dis= new BufferedReader ( new InputStreamReader (System.in));
    System.out.println ("Server menunggu input");
    InetAddress i=InetAddress.getByName ("Localhost");

    while (true) {
    System.out.print("Inputan Server: ");
    String str=dis.readLine();
    
    if ((str==null || str.equals ("end"))) break;
        buffer=str.getBytes();
        ds.send (new DatagramPacket (buffer,str.length(), i, clientport));
    } 
    } 
    
 }

3. Client Program

import java.net.*;
import java.io.*;

 class ClientDatagram {
    public static DatagramSocket d;
    public static byte buffer[] = new byte [1024];
    public static int clientport=800,serverport =900;

    public static void main (String args[]) throws Exception {
        d= new DatagramSocket (clientport);
        System.out.println ("Client sedang menunggu server mengirimkan data ");
        System.out.println ("tekan Ctrl + C untuk mengakhiri ");

        while (true) {
        DatagramPacket p = new DatagramPacket (buffer, buffer.length);
        d.receive (p);
        String ps= new String (p.getData(),0,p.getLength());
        System.out.println("From Server: "+ ps);
        } 
    } 
 }

Post a Comment

Previous Next

نموذج الاتصال