Skip to main content

Java Socket Basics(Socket Programming in Java) Part-2(UDP)

Hi friends,

We are going to discuss about UDP Socket Programming. In previous post we discussed about the differences between TCP & UDP and the sample example of TCP Socket Programming.

Below is the sample example of chat application using UDP Socket Programming.

UDP Sample:- We are going to create an small example which contains two classes.
  1. UdpServer.java:- This is a server class. Means this class will serve the purpose of socket connection. DatagramSocket is the java class and serve the purpose of Server and Client both. The overloaded constructor of DatagramSocket class matters. DatagramPacket is the java class which is responsible to transmit the data/packet over the network from server to client and vice-versa.
  2. UdpClient.java:- This is client class. This serves the purpose of client which will communicate to server and send data to server and receive the data sent by server.
UdpServer.java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;

public class UdpServer {

 public static void main(String[] args) {
  byte[] receiveBytes = new byte[256];
  final int SERVER_PORT = 8080;
  System.out.println("Server started. Waiting for client message...");
  try (DatagramSocket ds = new DatagramSocket(SERVER_PORT); Scanner sc = new Scanner(System.in);) {
   while (!ds.isClosed()) {
    // Construct Datagram packet to receive message
    DatagramPacket dp = new DatagramPacket(receiveBytes, receiveBytes.length);
    ds.receive(dp);
    String dataString = new String(dp.getData(), "UTF-8");
    System.out.println("Client Says:" + dataString);
    String input = sc.nextLine();
    // Construct Datagram packet to send message
    DatagramPacket sendPacket = new DatagramPacket(input.getBytes(), input.getBytes().length,
      dp.getAddress(), dp.getPort());
    ds.send(sendPacket);
   }
   ds.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}











UdpClient.java

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class UdpClient {

 public static void main(String[] args) {
  byte[] receiveBytes = new byte[256];
  final String TERMINATE = "bye";
  final int SERVER_PORT = 8080;
  System.out.println("Client started. Type a message and hit Enter key to send the message to server.");
  try (Scanner sc = new Scanner(System.in); DatagramSocket ds = new DatagramSocket();) {
   // Get server address
   final InetAddress SERVER_ADDRESS = InetAddress.getLocalHost();
   DatagramPacket dataPacket = null;
   while (!ds.isClosed()) {
    String input = sc.nextLine();
    // Terminate the client if user says "bye"
    if (input.trim().equalsIgnoreCase(TERMINATE)) {
     break;
    }
    // Construct Datagram packet to send message
    dataPacket = new DatagramPacket(input.getBytes(), input.getBytes().length, SERVER_ADDRESS, SERVER_PORT);
    ds.send(dataPacket);
    // Construct Datagram packet to receive message
    dataPacket = new DatagramPacket(receiveBytes, receiveBytes.length);
    ds.receive(dataPacket);
    System.out.println("Server Says:" + new String(receiveBytes, "UTF-8"));
   }
  } catch (SocketException | UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

This example works as Client->Server and Server->Client mechanism. Means this example describes two way communication between Client and Server. This is a simple chat application.

First compile and run UdpServer class and then UdpClient class.



Hope this will help you. Suggestions are most welcome. Keep visiting my blog :)

Comments

Post a Comment

You are responsible person and please write responsibly

Popular posts from this blog

app-policy

PRIVACY POLICY Last updated April 19, 2023 This privacy notice for Team CoderzDuniya ( " Company ," " we ," " us ," or " our " ), describes how and why we might collect, store, use, and/or share ( " process " ) your information when you use our services ( " Services " ), such as when you: Download and use our mobile application ( Revenue Calculator) , or any other application of ours that links to this privacy notice Engage with us in other related ways, including any sales, marketing, or events Questions or concerns?  Reading this privacy notice will help you understand your privacy rights and choices. If you do not agree with our policies and practices, please do not use our Services. If you still have any questions or concerns, please contact us at droidamar007@gmail.com . SUMMARY OF KEY POINTS This summary provides key points from our privacy notice, but you can find out more details about any of these t...

Amazon Bedrock - Creating a AI Agent

Creating an AI agent using Amazon Bedrock involves configuring foundation models, defining tools, and deploying an agent capable of interacting with users and systems. Below is a step-by-step guide with visual references and a clear explanation . Step 1: Understand Amazon Bedrock Architecture Core components: Foundation Model (FM) – Claude, Titan, Llama, etc. Agent – Orchestrates reasoning and actions Knowledge Base – Connects to your data (S3, PDFs, databases) Action Groups – Lambda functions for performing tasks Client Application – Web app, chatbot, or API Step 2: Enable Amazon Bedrock To enable the Amazon Bedrock -  Login to AWS Console Search → Amazon Bedrock Click → Model access Enable models like: Claude (best for agents) Titan Llama Step 3: Create Knowledge Base (Optional but Recommended) A knowledge base allows agents to use your custom data. To create a Knowledge Base -  Steps: Go to Bedrock Console Click → Knowledge Bases ...