Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5980837
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T21:51:29+00:00 2026-05-22T21:51:29+00:00

I’ve written two programs. Now each program uses threading to send and receive packets

  • 0

I’ve written two programs. Now each program uses threading to send and receive packets at the same time.
Whenever I send packets from the server to the client, the message at the client ends gets received in an infinite loop. I.e; I’ve added a print statement that prints the message sent and this goes forever in an infinite loop. I want to make it so that it receives the message, and then be able to write back to the server and exit whenever the user wants to.

I’ve tried using socket.close(), but this makes it so that the client receives the message and I can only write back to the server once. After I send it, I can’t send anymore. I want to make it so that I can write back more than once.

Can anyone please point me in the right direction?

My code is as follows;

public class UDPThreadClient extends Thread {

public static int port1;

//Create threaded server
UDPThreadClient (int port1) {
    System.out.println ("Starting threaded client");
    start();
}

public void run() {

    int port = port1;

    try {
        DatagramSocket serverSocket = new DatagramSocket(port1);
           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());
                 SocketAddress address = receivePacket.getSocketAddress();


                 System.out.println("RECEIVED from " + address + " : " + 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);
                 //serverSocket.close();
           }  
    } catch (IOException e) {
        System.out.println (e.getMessage());
    }

}

//Create client
public static void main(String[] args) {

    int port = Integer.parseInt(args[0]);
    port1 = Integer.parseInt(args[1]);
    new UDPThreadClient (port1);
    try {

          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, port);

          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();
    } catch (IOException e) {
        System.out.println (e.getMessage());
    }
}
   }

and

public class UDPThreadServer extends Thread {

public static int port1;

//Create threaded client
UDPThreadServer () {

    System.out.println ("Starting threaded server");
    start();


}

public void run() {

    try {
        DatagramSocket clientSocket = new DatagramSocket();

            BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in));
            Scanner in = new Scanner (inFromUser);
            InetAddress IPAddress = InetAddress.getByName("localhost");
        byte[] sendData = new byte [1024];
        byte[] receiveData = new byte [1024];

        while (in.hasNextLine()) {
        String sentence = in.nextLine();
        //inFromUser.readLine();
        sendData = sentence.getBytes();

        DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port1);
        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length);
        clientSocket.receive (receivePacket);

        String modSentence = new String (receivePacket.getData());
        System.out.println ("FROM SERVER: " + modSentence);
        }
        //clientSocket.close();
    } catch (IOException e) {
        System.out.println (e.getMessage());
    }

}

//Create server
public static void main(String[] args) {

    int port = Integer.parseInt(args[0]);
    port1 = Integer.parseInt(args[1]);
    new UDPThreadServer ();
    try {
        DatagramSocket serverSocket = new DatagramSocket (port);
        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());
            SocketAddress address = receivePacket.getSocketAddress();
            System.out.println ("Received from " + address + " : " + sentence);

            InetAddress IPAddress = receivePacket.getAddress();
            String capSentence = sentence.toUpperCase();
            sendData = capSentence.getBytes();
            DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port);
            serverSocket.send(sendPacket);
            //serverSocket.close();
        }

    } catch (IOException e) {
        System.out.println (e.getMessage());
    }
}

}

Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T21:51:30+00:00Added an answer on May 22, 2026 at 9:51 pm

    Looking at UDPClientServer:

    When you create the Datagram packet, you give it the port to send it to, not the port that you are sending it from.

    When I ran your code, nothing happened. The server is waiting on port port, while the client sends to port port1. If you instead send to port port (not accessible from the main method, but changing it to a field instead of local method would fix that, then the infinite looping occurs because the server sends a packet to the same port it is listening on. There’s your problem. Do you supply the same numbers as the first and second arguments to your program?

    From the server, you can use receivePacket.getPort() to get the port where the packet came from.

    EDIT:

    Your two classes have much repetition, which is probably a source of confusion. One class has a main which starts a client then creates a server type loop tester. The other class sets up a Server then creates a client type tester.

    Below is only the class you’ve named UDPThreadServer with comments showing changes to make the server ‘work’ with the testing code in the main method. Note that the server should send to a port that it is not listening to. You are also reading port values from command line arguments. I just made up some numbers for the ports and stuck them in as constants.

    public class UDPThreadServer extends Thread
    {
    
      public static int port1;
    
      UDPThreadServer()
      {
        //server or client?  it's hard to say.  you call the socket a clientSocket.
        System.out.println("Starting threaded server");
        start();
      }
    
      public void run()
      {
        try
        {
          // Here client(?) is set up with empty constructor.
          // It is a mystery what port it will get.
          DatagramSocket clientSocket = new DatagramSocket();
    
          BufferedReader inFromUser =
              new BufferedReader(new InputStreamReader(System.in));
          Scanner in = new Scanner(inFromUser);
          InetAddress IPAddress = InetAddress.getByName("localhost");
          byte[] sendData = new byte[1024];
          byte[] receiveData = new byte[1024];
    
          while (in.hasNextLine())
          {
            String sentence = in.nextLine();
            // inFromUser.readLine();
            sendData = sentence.getBytes();
    
            // sending to port1?  that must be the server.
            DatagramPacket sendPacket =
                new DatagramPacket(sendData, sendData.length, IPAddress, port1);
            clientSocket.send(sendPacket);
    
            DatagramPacket receivePacket =
                new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);
    
            String modSentence = new String(receivePacket.getData());
            System.out.println("FROM SERVER: " + modSentence);
          }
          // clientSocket.close();
        } catch (IOException e)
        {
          System.out.println(e.getMessage());
        }
      }
    
      // Create server
      public static void main(String[] args)
      {
    
        // int port = Integer.parseInt(args[0]);
        int port = 1927; // or whatever
        // port1 = Integer.parseInt(args[1]);
        port1 = 1928;
        new UDPThreadServer();
        try
        {
          // server resides on port1?  if client sends to port 1, then this is so.
          DatagramSocket serverSocket = new DatagramSocket(port1);
          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());
            SocketAddress address = receivePacket.getSocketAddress();
            System.out.println("Received from " + address + " : " + sentence);
    
            InetAddress IPAddress = receivePacket.getAddress();
            String capSentence = sentence.toUpperCase();
            sendData = capSentence.getBytes();
    
            // where did you get the info from?  Client is set up with an empty constructor, so it is a mystery.
            port = receivePacket.getPort();
    
            DatagramPacket sendPacket =
                new DatagramPacket(sendData, sendData.length, IPAddress, port);
            serverSocket.send(sendPacket);
            // serverSocket.close();
          }
    
        } catch (IOException e)
        {
          System.out.println(e.getMessage());
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.