?
Solved

IndexOutOfBoundsException Problem

Posted on 2005-03-04
7
Medium Priority
?
413 Views
Last Modified: 2008-03-17
I'm currently making a chat room where i have a server.java file and a client.java file.2 users can connect to the server successfully,and send a few messages between each other.the problem is that after a random amount of messages the following exception error occurs on the server window:

Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException: end
        at java.util.regex.Matcher.region(Matcher.java:882)
        at java.util.Scanner.findPatternInBuffer(Scanner.java:964)
        at java.util.Scanner.findWithinHorizon(Scanner.java:1594)
        at java.util.Scanner.findWithinHorizon(Scanner.java:1551)
        at java.util.Scanner.nextLine(Scanner.java:1457)
        at AssignmentServer$ClientHandler.run(AssignmentServer.java:65)

after that error appears,the user that thread is associated with cannot send anymore messages,however,they can still received messages sent by other users.
i personally don't understand what it means and how to fix it.i've only beens tudying java for a few months so don't have the required knowledge to fix it so any help is appreciated!
if any code is required then just ask and i'll give you it
0
Comment
Question by:smhouston
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 13460607
Hi.

Could we see some code please?
I'm mainly after lines 60 to 70 in AssignmentServer.java please?

Cheers,
>> IM
0
 

Author Comment

by:smhouston
ID: 13463652
i've been using textpad to do the code so i've given you lines 57 to 84 as i understand java and textpad numbering aren't the same?

            [CODE]public void run()
            {
                  String received;
                  Socket client2;


                  do
                  {
                        received = input.nextLine();

                        for(int i = 0; i <= AssignmentServer.clientSocket.size()-1; i++)
                        {
                              try
                              {
                                    client2 = AssignmentServer.clientSocket.elementAt(i);
                                    System.out.println("#1 " + client2);
                                    PrintWriter output = new PrintWriter(client2.getOutputStream(),true);
                                    //output = new PrintWriter(client2.getOutputStream(),true);
                                    output.println(received);
                                    System.out.println(received);
                              }
                              catch(IOException e)
                              {
                                    System.err.println(e);
                              }
                        }

                  }while (!received.equals("QUIT"));[/CODE]
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 13465095
> as i understand java and textpad numbering aren't the same?
They should be.. I know for fact that Notepad, and just about every other IDE has correct line numbering..

Back to the problem now...

Hmm.. I could only make a wild guess there.. Could you post the full content of the class "ClientHandler" (from within the AssignmentServer), please?

Ta,
>> IM
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

Author Comment

by:smhouston
ID: 13465116
sure...

private static class ClientHandler extends Thread
      {
            
            public void run()
            {
                  String received;
                  Socket client2;


                  do
                  {
                        received = input.nextLine();

                        for(int i = 0; i <= AssignmentServer.clientSocket.size()-1; i++)
                        {
                              try
                              {
                                    client2 = AssignmentServer.clientSocket.elementAt(i);
                                    System.out.println("#1 " + client2);
                                    PrintWriter output = new PrintWriter(client2.getOutputStream(),true);
                                    //output = new PrintWriter(client2.getOutputStream(),true);
                                    output.println(received);
                                    System.out.println(received);
                              }
                              catch(IOException e)
                              {
                                    System.err.println(e);
                              }
                        }

                  }while (!received.equals("QUIT"));

                  try
                  {
                        System.out.println("Closing down connection...");
                        client.close();
                        for (int x = 0; x <= AssignmentServer.clientSocket.size()-1; x++)
                        {
                              Socket socketIP = AssignmentServer.clientSocket.get(x);

                              if (socketIP.equals(client))
                              {
                                    AssignmentServer.clientSocket.removeElementAt(x);
                                    System.out.println("Client deleted");
                              }

                              System.out.println(AssignmentServer.clientSocket.elementAt(x));
                        }
                  }
                  catch(IOException e)
                  {
                        e.printStackTrace();

                  }

            }
      }
0
 
LVL 25

Accepted Solution

by:
InteractiveMind earned 240 total points
ID: 13465227
Okay, I can't see exactly what is causing this problem. But it would appear to me that it could be avoided, if you were to use a more efficient method of handling connections..

Allow me to demonstrate...


Rather than creating an array of Sockets, to handle clients - you should just do something like this instead (in the main Server instance):

...
int port = 80;
ServerSocket srv = new ServerSocket(port);

for ( ;; ) {     // Infinite loop
     try
     {
          new ClientHandler(srv.accept()).start();
     } catch (Exception e)
     {
          e.printStackTrace();
     }
}
...


Then, you'd use something like this for the ClientHandler:


public static class ClientHandler extends Thread
{
     private Socket client;
     
     public ClientHandler( Socket client )
     {
          this.client = client;
     }
     
     public void run ()
     {
          try
          {
               String recieved;
               // Perform operations on 'client' variable here . . .
          } catch (Exception e)
          {
               e.printStackTrace();
          }
     }
}


This really is the best method... This way, also, you can handle an unlimited number of connections.. And if you need to control each connection individually, just pass a unique number to each ClientHandler, and then use a Vector or Hashmap (or some other instance of Map), to pass commands to the thread..

Make sense at all?

Hope that helps.. If you *really* want to stick with what you're doing still though, then I can't really figure it.. so, you'd be best having this thread moved to the Java TA, where they will almost certainly be able to find a solution -- but I'm sure most of them would make the same recommendation as I have above (about changing your technique).

Regards,
>> IM
0
 

Author Comment

by:smhouston
ID: 13466052
i'm just doing what our lecturer tells us,and from what i'm finding out so far he's not teaching us the best possible methods so far!

i think i understand what you mean,but once i receive the message from a client,how do i pass it out to all the clients?as i did that using the vector last time and going through each client in the vector
0
 

Author Comment

by:smhouston
ID: 13466191
i've actually just managed to get it to work :-) when i was modifying the server a few weeks ago i moved some of the information from the clienthandler.i've just put it back in and it works so far *touch wood*.i've also took your advice on board,and even though i've still done the method different to what you recommend,i've implemented the never ending for loop.thanks alot for your help :-) the code now looks like the following:

import java.net.*;
import java.io.*;
import java.util.*;

public class AssignmentServerNew
{
      private static InetAddress host;
      private static ServerSocket servSocket;
      private static final int PORT = 1234;
      private      static String text = "";
      private static Vector<Socket> clientName = new Vector<Socket>();
      private static Vector<Socket> clientSocket = new Vector<Socket>();


      public static void main(String[] args) throws IOException
      {
            try
            {
                  servSocket = new ServerSocket(PORT);
            }
            catch (IOException e)
            {
                  System.out.println("\nUnable to set up port!");
                  System.exit(1);
            }

            for(;;)
            {
                  System.out.println("**************** SERVER RUNNING ****************");
                  Socket client = servSocket.accept(); //Wait for client.
                  host = client.getInetAddress();
                  System.out.println("\nNew client accepted with IP Address of" + host);
                  ClientHandler handler = new ClientHandler(client);
                  handler.start();
            }

      }

      public static class ClientHandler extends Thread
      {
            private Socket client;
            private Scanner input;
            private PrintWriter output;

            public ClientHandler(Socket socket) throws IOException
            {
                  client = socket;
                  String clientUsername;
                  clientSocket.add(client);
                  input = new Scanner(client.getInputStream());
                  clientUsername = input.nextLine();
                  System.out.println(clientUsername);
            }

            public void run()
            {
                  String received;
                  Socket client2;

                  do
                  {
                        received = input.nextLine();
                        System.out.println(received);

                        for(int i = 0; i <= AssignmentServerNew.clientSocket.size()-1; i++)
                        {
                              try
                              {
                                    client2 = AssignmentServerNew.clientSocket.elementAt(i);
                                    PrintWriter output = new PrintWriter(client2.getOutputStream(),true);
                                    output.println(received);

                              }
                              catch(IOException e)
                              {
                                    System.err.println(e);
                              }
                        }

                  }while (!received.equals("QUIT"));

                  try
                  {
                        System.out.println("Closing down connection...");
                        client.close();
                        for (int x = 0; x <= AssignmentServerNew.clientSocket.size()-1; x++)
                        {
                              Socket socketIP = AssignmentServerNew.clientSocket.get(x);

                              if (socketIP.equals(client))
                              {
                                    AssignmentServerNew.clientSocket.removeElementAt(x);
                                    System.out.println("Client deleted");
                              }

                              System.out.println(AssignmentServerNew.clientSocket.elementAt(x));
                        }
                  }
                  catch(IOException e)
                  {
                        e.printStackTrace();

                  }

            }

      }
}
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question