Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

UDP Server in Java

                         

Providing you information relating to all technicalities of UDP server. This section provides you the brief description and program of the UDP server only for received your messages or information.

The UDP server 
UDP denotes a computing and technical terms that stands for User Datagram Protocol. Usually functioning as a connectionless datagram services with no guarantee of delivering data in a particular sequence. Any source host that requires a reliable communication has options of using either TCP or a program based on a sequential services. Generally all UDP messages are sent with the current IP address through ports. It helps in delivering messages from the source host to the ultimate destination as a postcard; small but not with a guarantee of delivery but TCP works like a telephone by verifying the destination address. Usually UDP is used to deliver a small amount of data to a large number of recipient at one set period of time. So it low over heading and multitasking capacity stands it ahead than TCP.

The Datagram 
The datagram is an unite of packet or packet for transfer in the TCP/IP network. Each datagram packet has data with source and destination address.

Description of program:

When you will run the program then a layout will appear on the screen that contains two buttons 'Start' and 'Stop' with a text area, where you receive your messages. The messages can be received only on that time when the UDP server is started. Whenever the UDP server is stopped then you can't be sent any message by the UDP client. If UDP server is started then it display the the message "Server is started" in the text area otherwise it shows "Server is stopped" or no any message in the text area.

Description of code:

Thread():
Thread is a constructor of Thread class. The Thread class extends the Object and implements the Runnable. It creates a new thread object. Where you require, the executing of program continuously you can be used thread.

thread.start():
This method starts the thread for executing the program. The run() method is called automatically when the start() method is execute.

thread.interrupted():
The above method interrupts the thread that means breaking the thread for some time. If you want to start the thread again you can start it.

DatagramSocket(int port):
DatagramSocket is the constructor of DatagramSocket class. This class extends Object. It creates the datagram socket and takes only integer  port number. This socket binds the specified port number where the messages is send on the local host machine.

append(String str):
This method is used to insert or append given the string in it.

DatagramPacket(byte[] buffer, int buffer_length):
This constructor provided by the DatagramPacket class. This class extends the Object and imports the java.net.*. It constructs a DatagramPacket to the receiving packet length. It takes the buffer size and buffer length. Where the connectionless services are provided by the user then use it. 

receive(DatagramPacket packet):
The datagram packet received by this method from the specified socket.

InetAddress:
This class extends the Object and implements the Serializable. It displays the IP address. 

getAddress():
Above method returns the IP address of the object of InetAddress class, where the datagram packet can be send or receive.

getPort():
This method returns the port number of the host machine. Where the datagram packets can be send or receive.

socket.close():
This method closes the datagram socket that means you can not be received any messages.

Here is the code of program: 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class UDPServer{
  JFrame frame;
  JPanel panel;
  JButton button1,button2;
  JTextArea area;
  JScrollPane pane;
  Thread thread;
  DatagramSocket socket;

  public static void main(String[] args) {
    UDPServer u = new UDPServer();
  }
  public UDPServer(){
    frame = new JFrame("Text Server");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(true);
    frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
    panel = new JPanel();
    panel.setLayout(null);
    area = new JTextArea();
    area.setEditable(false);
    button1 = new JButton("Start");
    button1.setBounds(210107540);
    button1.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
        new StartThread();
      }
    });
    panel.add(button1);
    button2 = new JButton("Stop");
    button2.setBounds(300107540);
    button2.addActionListener(new ActionListener(){
      public void actionPerformed (ActionEvent ae){
        thread.interrupted();
        socket.close();
        area.append("Server is stopped\n");
        button1.setEnabled(true);
        button2.setEnabled(false);
      }
    });
    button2.setEnabled(false);
    panel.add(button2);
    pane = new JScrollPane(area);
    pane.setBounds(1060365250);
    panel.add(pane);
    frame.add(panel);
    frame.setSize(400400);
    frame.setVisible(true);
  }
  public class StartThread implements Runnable{
    StartThread(){
      thread = new Thread(this);
      thread.start();
      button1.setEnabled(false);
      button2.setEnabled(true);
    }
  public void run(){
      try{
        byte[] buffer = new byte[1024];
        int port = 8080;
        try{
        socket = new DatagramSocket(port);
        while(true){
        try{
          area.append("Server is started\n");
          //Receive request from client
          DatagramPacket packet = new DatagramPacket(buffer, buffer.length );
          socket.receive(packet);
          InetAddress client = packet.getAddress();
          int client_port = packet.getPort();
          area.append(" Received "+new String(buffer)+" from "+client);
          
        }
        catch(UnknownHostException ue){}
        }
        }
        catch(java.net.BindException b){}
      }
      catch (IOException e){
        System.err.println(e);
      }
    }
  }
}

Download this example.

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Latest Searches:
goto
goto line
ASP EXAMPLE and char(1
include a file in dire
open close session
struts custom tag
insert data to html fi
resultsetmethods
how to split string c
break?ΠΆΠ????????ΠΆΠ??
asterisk
jQuery To Hide the Div
stored procedure in hi
how to reference index
session bean
Java EJB EJB exception
div
syntax
Contenttype
client/server
struts validation fram
HSSF clone cell
j2me insert image usin
insert loop
command Sort Header on
Quartz
java program to transp
redirecting
jsp
out in jsp
difference between arr
sample
java ????ΆΡ????? ?????
javaclient/serverprogr
static
actionperformed
insert data tohtml fil
clipiing source code i
html to pdf
GetCharFromString usin
how to write in pdf us
j2me datefield
errors
clear values from a fo
write a xml file using
struts supported jar f
session.set attribute(
append message
types of heap sort
sort object compareTo
call javascript throug
File
using the selection so
DefaultMutableTreeNode
floating point
<select><option> jsp d
changehashtablevalue
Netbeans JSF
JSP:File Field
events in jsp
string variable
Create Scroll Bar in J
netbens jsf
call name in java usin
java keyword
JSLT Example
create excel using in
how to iterate the str
Jmenu in java
stopwacth
facelets
daouble in java
.setDocument(new
view record by charact
Combo Box operation in
storing text data to a
browse an image from h
Java example program t
WebObjects
treeview structure cod
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.