Error with server

Joined
Jun 14, 2021
Messages
5
Reaction score
0
I run my java server and receive an error, I am not sure how to fix it and wish to receive recommendations on how to fix it. The following is shown indicating line 39 in my code.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

Code:
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {
   private ServerSocket serverSocket;
  
   public GreetingServer(int port) throws IOException {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }

   public void run() {
      while(true) {
         try {
            System.out.println("Waiting for client on port " +
               serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            
            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
               + "\nGoodbye!");
            server.close();
            
         } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
         } catch (IOException e) {
            e.printStackTrace();
            break;
         }
      }
   }
  
   public static void main(String[] args) {
      int port = Integer.parseInt(args[0]);
      try {
         Thread t = new GreetingServer(port);
         t.start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}
 
Joined
Apr 25, 2017
Messages
251
Reaction score
33
What do you want this line to do ?

Java:
int port = Integer.parseInt(args[0]);
 
Joined
Jun 14, 2021
Messages
5
Reaction score
0
Yes I want to pass in the arguments, being the hostname and port. Then it should be args[2] although I receive an exception after compiling successfully then running 'java GreetingServer hostname 22'.
Code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
    at GreetingServer.main(GreetingServer.java:39)
 
Joined
Mar 28, 2022
Messages
82
Reaction score
11
Java:
public static void main(String[] args) {
      System.out.println(args[0]); // debug
      int port = Integer.parseInt(args[0]);
      try {
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top