Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: UDP Server Client program to send and receive messages

  1. #1
    Member
    Join Date
    Mar 2009
    Posts
    48
    Thanks
    3
    Thanked 2 Times in 2 Posts

    Default UDP Server Client program to send and receive messages

    Hallo, I want that client send massage to server and server massage send back to client. But I don´t know how can i do in server thread: ThreadForwarding. Do you have some idea? Thank you.
    package nserver;
     
    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.Arrays;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    /**
     *
     * @author Lolek
     */
     
    public class Main {
     
        /**
         * @param args the command line arguments
         */
     
        public static void main(String[] args){       
     
                Port port = new Port();
                Address address = new Address();
                Forwarding forwarding = new Forwarding();
     
                ThreadForwarding odesli = new ThreadForwarding (port, address, forwarding);
                ThreadReciving prijem = new ThreadReciving(5000, port, address, forwarding);
     
         }    
      }
     
     
     
    class ThreadReciving extends Thread
    {   
     
     
        private Port p;
        private Address a;
        private int getPort;
        private InetAddress getAddress;
        private Forwarding forwarding; 
        private byte send[] = new byte[256];
        private byte sendData[] = new byte[256];
        private byte[] recived = new byte[256];
     
        DatagramSocket server;
     
        int port;   
        ThreadReciving(int port,Port p,Address a,Forwarding forwarding)
        {   
            try {
                this.forwarding = forwarding;
                this.a = a;
                this.p = p;
                this.server = new DatagramSocket(port);
                new Thread(this, "ThreadReciving").start();
            } catch (SocketException ex) {
                Logger.getLogger(ThreadReciving.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        @Override
        public void run ()
        {    
     
            try 
            {            
                while(true)
                {
     
                 DatagramPacket recivedPacket = new DatagramPacket(prijata,prijata.length);
                 server.receive(recivedPacket);
     
                 String recivedStr = new String(recivedPacket.getData(),0,recivedPacket.getLength());
     
                 send = recived.getBytes();
                 forwarding.setData(odeslana);
     
                 if (recived.equals("add"))
                 {
                    getPort = recivedPacket.getPort();            
                    p.setData(getPort);               
     
     
                    getAddress = recivedPacket.getAddress();
                    a.setData(getAddress);                                
                 }
     
     
                 System.out.println("client:"+recived);
                }            
            } 
            catch (IOException ex) 
            {
                Logger.getLogger(ThreadReciving.class.getName()).log(Level.SEVERE, null, ex);
            }    
        }
    }
     
     
    class ThreadForwarding extends Thread
    {
     private Forwarding forwarding;
     private InetAddress client;
     private int port;
     private DatagramSocket server;
     private Port p;
     private Address a;
     
     VlaknoPreposilaci(Port p,Address a,Forwarding forwarding)
     {
            try {
                this.forwarding = forwarding;
                this.p = p;
                this.a = a;
                this.server = new DatagramSocket();           
                new Thread(this, "ThreadForwarding").start();
            } catch (SocketException ex) {
                Logger.getLogger(ThreadForwarding.class.getName()).log(Level.SEVERE, null, ex);
            }
     }
     
        @Override
     public void run()
     {  p.getData();
        a.getData();
        prepos.getData();
     
     
       // while(true)
       // {   
                try {
     
     
     
     
                    DatagramPacket ForwardingPacket = new DatagramPacket(forwarding.send, forwarding.send.length, a.addressArray[0], p.addressArray[0]);
                    server.send(ForwardingPacket);
                } catch (IOException ex) {
                    Logger.getLogger(ThreadForwarding.class.getName()).log(Level.SEVERE, null, ex);
                }
     
        //}
     }
     
    }
     
     
    class Port {
        private int portt;
        private int i;
        private int n = 0;
        private boolean bool = true;
        private boolean stop = false;
     
        int portArray[] = new int[10];
        public synchronized void setData(int portt){
            if(stop)
            {
                try {
                    wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Port.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            stop=true;
            Arrays.fill(portArray, n);
            for(int x=0;x<10;x++)
            {
                if((portArray[x]==n)&&(bool==true))
                {
                     this.portArray[x]=portt;
                     bool = false;             
                }
            }
            System.out.println(this.portArray[0]);
            notify();                                  
            }
     
        public synchronized int[] getData(){        
          if(!stop)
          {
                try {
                    wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Port.class.getName()).log(Level.SEVERE, null, ex);
                }
          }
          stop=false;
          notify();
          return portArray; 
        }
    }
    class Adrress {
     
        private boolean stop=false;
        private boolean bool=true;
        private int i;
        byte[] ip={Network.ip(100),Network.ip(100),Network.ip(100),Network.ip(100)};    
     
        InetAddress addressAray[]=new InetAddress[10];
     
        public synchronized void setData(InetAddress address){
            try {
                InetAddress plnAddress = InetAddress.getByAddress(ip);
                if (stop) {
                    try {
                        wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Address.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                stop = true;
                Arrays.fill(addressAray, plnAdres);
                for (i = 0; i < 10; i++) {
                    if ((addressAray[i] == plnAddress) && (bool)) {
                        this.addressAray[i] = address;
                        bool = false;
                    }
                }
                System.out.println(this.addressArray[0]);
                notify();
            } catch (UnknownHostException ex) {
                Logger.getLogger(Address.class.getName()).log(Level.SEVERE, null, ex);
            }
            }
     
     
        public synchronized InetAddress[] getData(){
            if(!stop)
            {
                try {
                    wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Address.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            stop=false;
            notify();
            return addressAray;
        }
    }
     
    class Forwarding {
        private boolean stop=false;
        byte[] send = new byte[256];
        private int i;
        public synchronized void setData(byte send[]){
            if(stop)
            {
                try {
                    wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Forwarding.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            stop=true;
            this.send=send;        
            notify();
            }
     
        public synchronized byte[] getData(){
           if(!stop)
           {
                try {
                    wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(Forwarding.class.getName()).log(Level.SEVERE, null, ex);
                }
           }
           stop=false;
           notify();
           return send;
        }
    }
     
     
     
     
    class Network {
    public static byte ip(int i) {
    return (byte) ((i > 127) ? i - 256 : i);
    }
    }
    and client
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package nklient;
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    /**
     *
     * @author Lolek
     */
    public class Main {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            try {
                //byte[] ip = {Network.ip(172), Network.ip(0), Network.ip(0), Network.ip(1)};
                //InetAddress adresa = InetAddress.getByAddress(ip);
     
                String hostname = "localhost";
                InetAddress ia = InetAddress.getByName(hostname);
     
                SendThread send = new SendThread(ia, 5000);
                send.start();
     
                ReciveThread recive = new ReciveThread(send.getSocket());
                recive.start();
            } catch (UnknownHostException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
     
    }
    class SendThread extends Thread
    {
        private InetAddress server;
        private DatagramSocket client;
        private int port;
        private byte addPacket[]=new byte[3];
        private String test="add";
        public SendThread(InetAddress address,int port)
        {
            try {
                this.server = address;
                this.port = port;
                this.client = new DatagramSocket();
                this.client.connect(address, port);
     
            } catch (SocketException ex) {
                Logger.getLogger(SendThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        public DatagramSocket getSocket()
        {
            return this.client;
        }
        @Override
        public void run()
        {
            try {
                addPacket = test.getBytes();
                DatagramPacket testPacket = new DatagramPacket(addPacket, addPacket.length, server, port);
                client.send(testPacket);
                BufferedReader cteni = new BufferedReader(new InputStreamReader(System.in));
                while (true) {
                    try {
     
                        String reading = cteni.readLine();
                        if (reading.equals("/q")) {
                            break;
                        }
                        byte[] data = reading.getBytes();
                        DatagramPacket odesilanaData = new DatagramPacket(data, data.length, server, port);
                        client.send(odesilanaData);
                    } catch (IOException ex) {
                        Logger.getLogger(SendThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(SendThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
     
    class  ReciveThread extends Thread
    {
        DatagramSocket client;
     
     
        public  ReciveThread (DatagramSocket pomA)
        {
            this.client=pomA;
        }
     
        @Override
        public void run()
        {
            byte[] reciveData = new byte[256];
            while (true)
            {
                try {
     
                    DatagramPacket reciving = new DatagramPacket(reciveData, reciveData.length);
                    client.receive(reciving);
                    String here = new String(reciving.getData(), 0, reciving.getLength());
                    System.out.println(here);
                } catch (IOException ex) {
                    Logger.getLogger(ReciveThread.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
     
     
    class Network {
    public static byte ip(int i) {
    return (byte) ((i > 127) ? i - 256 : i);
    }
    }


  2. #2

    Default Re: UDP server

    I know this is late, but...

    I think you went a bit overboard.

    Start simple to ensure you have the foundation working well.

    Server
    import java.io.*;
    import java.net.*;
     
    class UDPServer
    {
       public static void main(String args[]) throws Exception
          {
             DatagramSocket serverSocket = new DatagramSocket(9876);
                byte[] receiveData = new byte[1024];
                byte[] sendData = new byte[1024];
                while(true)
                   {
                      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                      serverSocket.receive(receivePacket);
                      String sentence = new String( receivePacket.getData());
                      System.out.println("RECEIVED: " + sentence);
                      InetAddress IPAddress = receivePacket.getAddress();
                      int port = receivePacket.getPort();
                      String capitalizedSentence = sentence.toUpperCase();
                      sendData = capitalizedSentence.getBytes();
                      DatagramPacket sendPacket =
                      new DatagramPacket(sendData, sendData.length, IPAddress, port);
                      serverSocket.send(sendPacket);
                   }
          }
    }

    Client
    import java.io.*;
    import java.net.*;
     
    class UDPClient
    {
       public static void main(String args[]) throws Exception
       {
          BufferedReader inFromUser =
             new BufferedReader(new InputStreamReader(System.in));
          DatagramSocket clientSocket = new DatagramSocket();
          InetAddress IPAddress = InetAddress.getByName("localhost");
          byte[] sendData = new byte[1024];
          byte[] receiveData = new byte[1024];
          String sentence = inFromUser.readLine();
          sendData = sentence.getBytes();
          DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
          clientSocket.send(sendPacket);
          DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
          clientSocket.receive(receivePacket);
          String modifiedSentence = new String(receivePacket.getData());
          System.out.println("FROM SERVER:" + modifiedSentence);
          clientSocket.close();
       }
    }

    A Simple Java UDP Server and UDP Client | systemBash
    Kenneth Walter
    Software Developer
    http://kennywalter.com