StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Saturday, August 30, 2014

Java UDP Sockets

 August 30, 2014     Java     No comments   

UDP Introduction

TCP/IP sockets explained in this article is a reliable form of communication. However there is additional overhead involved in terms of error handling, congestion control etc. in TCP/IP communication. The other alternative available is to use UDP (User Datagram Protocol). UDP protocol doesn't guarantee that the message sent is transmitted reliably. Since UDP involves less overhead it is used in applications like video conferencing where real time performance is needed.

Java supports APIs to work with datagrams. There are 2 key classes DatagramSocket and DatagramPacket which are key elements to work with UDP protocol.

  1. DatagramSocket -A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently, and may arrive in any order.
  2. DatagramPacket - Datagram packets are used to implement a connectionless packet delivery service. Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order. Packet delivery is not guaranteed.

UDP (Datagram) server example in Java

In this example we implement a simple Datagram server. We construct a DatagramSocket and bind to a specific port on the local machine. Then we construct a DatagramPacket to receive packets. The receive call is a blocking call and waits till any packet is received from the client. When the receive method returns, the DatagramPacket's buffer is filled with the data received. Then we print the received contents.
package com.sourcetricks.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer {

  public static void main(String[] args) {
    final int port = 2222;
    byte buffer[] = new byte[1024];
    
    try ( DatagramSocket socket = new DatagramSocket(port); ) {
      while ( true ) {
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);
        System.out.println("Message received: " + new String(packet.getData()));
      }
    } catch (IOException e) {
      e.printStackTrace();
    } 
  }
}

UDP (Datagram) client example in Java

Datagram client example constructs a datagram packet for sending packets of specified length to the specified port number on the specified host. Finally we do the send call on the DatagramSocket to send the datagram to the server.
package com.sourcetricks.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {

  public static void main(String[] args) {
    final int destPort = 2222;

    byte buffer[] = new byte[1024];
    
    try ( DatagramSocket socket = new DatagramSocket(); ) {
      String str = "Hello UDP server";
      buffer = str.getBytes();
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length, 
          InetAddress.getLocalHost(), destPort);
      socket.send(packet);
      Thread.sleep(2000);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } 
  }
}
Continue to read other Java tutorials from here.
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk