1

I am trying to create a java chat and I got this bug: When I use name = scanner.nextLine() my program works apparently fine (but it's not reading any name, if I use System.out.println(name) I get newline), and when I don't use it my pg automaticly connects to server with no name. Can anyone tell me why it;s happening this?

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

class Cient 
{  
    static String name;

      public static void main(String[] args) throws Exception
      {
          Scanner scanner = new Scanner(System.in); 
          System.out.print("Adresa serverului si portul : ");//server adress and port
          Socket cs = new Socket( scanner.next(), scanner.nextInt() ); 
          DataOutputStream os = new DataOutputStream( cs.getOutputStream()); 
          final DataInputStream is = new DataInputStream( cs.getInputStream());
          String st = "";

            System.out.println("Va rugam sa va introduceti numele");//get name
            name = scanner.nextLine();
          Thread T= new Thread(new Runnable()
          {  
                 public void run() {
                  while (true)
                  {
                      String s = ""; 
                      try
                      {
                          s = is.readUTF();
                          System.out.println(s); 
                          if(s.equals("Intrerupem conexiunea .... Pa!"))//close connexion
                          {
                              return;
                          }
                      } catch (IOException ex)
                      {

                      }

                  }
              }
          });

          T.start();
          while (true) 
          { 
              st = scanner.nextLine();
              os.writeUTF(st);

              if(st.equals("QUIT") || st.equals("EXIT"))
              {
                  return;//stop reading
              }
          }
      }
}

Here is the Server Class, but I dont believe that's important:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Vector;

public class MyServer 
{
    Scanner scanner;
    Vector<String> users = new Vector<String>();
    Vector<HandleClient> clients = new Vector<HandleClient>();
    String disconnectedUser = "InvalidUser";//String care imi spune daca un client s-a razgandit la conectare
    int PORT;  

  public Vector<String> getUserList()
  {
      return users;
  }

  public void process() throws Exception  
  {
      scanner = new Scanner(System.in);
      System.out.println("PORT: ");

      PORT = scanner.nextInt();
      ServerSocket server = new ServerSocket(PORT);
      System.out.println("Server Online...");
      while(true) 
      {
         Socket client = server.accept();
         HandleClient c = new HandleClient(client);
         if(!(c.userName().equals(disconnectedUser)))
         {
             clients.add(c);
             users.add(c.userName());
         }
     }
  }

  public static void main(String ... args) throws Exception 
  {
      new MyServer().process();
  } 

  public void  broadcast(String user, String message)throws Exception  
  {
        for (HandleClient c : clients)
           if (!(c.userName().equals(user)))
           {
              c.sendMessage(user,message);
           }
  }

  public void twoUsersBroadcast(String fromUser,String toUser, String msg)throws Exception
  {
      for(HandleClient c : clients)
      {
        String a = (String) c.userName();
        if(a.equals(toUser))
        {
          c.sendMessage(fromUser,msg);
          return ;
        }
      }
  }

  public void changeUserName(String actualName,String newName)
  {
    int i = 0;
    for(HandleClient c: clients)
    {
      if(c.userName().equals(actualName))
      {
        c.setUserName(newName);
        users.set(i,newName);
      }
      i++;
    }
  }


  boolean validUserName(String name)
  {
    for(String c : users)
    {
      if(c.equals(name))
      {
        return false;
      }
    }
    return true;
  }

  class HandleClient extends Thread 
  {
    String name = "";
    DataInputStream input;
    DataOutputStream output;

    public String userName() 
    {
        return name;
    }

    public void setUserName(String name)
    {
        this.name = name;
    }

    public void writeError(String message)
    {
        try 
        {
            output.writeUTF("EROARE: " + message);
        }
        catch (IOException e) 
        {
            System.out.print(e.getMessage());
        }
    }

    public HandleClient(Socket client)throws Exception
    {
        input = new DataInputStream(client.getInputStream());
        output= new DataOutputStream(client.getOutputStream());

        boolean ok = true;

        while(ok == true)
        {
            name = input.readUTF();
            if(name.equals("EXIT"))
            {
                ok = false;
                output.writeUTF("Intrerupem conexiunea .... Pa!");
                name = "InvalidUser";//User-ul a renuntat la conexiune
            }
            else
            {
                if(validUserName(name) == true)
                {
                    ok = false;
                }
                else
                {
                    output.writeUTF("Numele este deja folosit. Va rugam sa introducet un alt nume sau EXIT in care doriti sa nu va mai conectati");
                }
            }
        }
        if("InvalidUser".equals(name))
        {

            return;
        }
          start(); 
    }

    public void sendMessage(String username,String  msg)throws Exception  
    {
        output.writeUTF( username + ": " + msg);
    }

    public void run()  
    {
         String line;
         try    
         { 
            boolean ok = true;
            output.writeUTF("Introduceti:");
            output.writeUTF("LIST pentru a vedea lista de utilizatori");
            output.writeUTF("MSG pentru a transmite un mesaj unui anumit utilizator");
            output.writeUTF("BCAST pentru a transmite un mesaj tuturor utilizatorilor");
            output.writeUTF("NICK pentru a va schimba numele");
            output.writeUTF("QUIT pentru a va deconecta de la server");

            while(ok == true)   
            {
                line = input.readUTF();
                switch(line)
                {
                    case "LIST":
                    {

                        Vector<String> users = getUserList();
                        output.writeUTF("Lista user-ilor este:");
                        for(String c : users)
                        {
                            output.writeUTF(c);
                        }
                        break;
                    }

                    case "MSG":
                    {
                        output.writeUTF("Introduceti numele persoanei careia doriti sa-i trimiteti mesajul");
                        line = input.readUTF();
                        if(validUserName(line) == true)
                        {
                            writeError("Numele persoanei nu exista");
                            break;
                        }
                        else
                        {
                            if(name.equals(line))
                            {
                                writeError("Selectati alt user");
                                break;
                            }
                            else
                            {
                                output.writeUTF("Introduceti mesajul pe care il aveti de transmis");
                                String message = input.readUTF();
                                if((validUserName(line) == false) && !(line.equals(name)))
                                {
                                    twoUsersBroadcast(name,line,message);
                                }
                                break;
                            }
                        }
                    }

                    case "BCAST":
                    {
                        line = input.readUTF();
                        broadcast(name,line);
                        break;
                    }

                    case "NICK":
                    {
                        output.writeUTF("Va rugam sa va introduceti numele dorit");
                        line = input.readUTF();

                        if(validUserName(line))
                        {
                            changeUserName(name,line);
                        }
                        else
                        {
                            writeError("Invalid username");
                        }
                        break;
                    }

                    case "QUIT":
                    {
                        output.writeUTF("Intrerupem conexiunea .... Pa!");
                        clients.remove(this);
                        users.remove(name);
                        ok = true;
                        break;
                    }

                    default:
                    {
                        writeError("Comanda incorecta");
                    }
                }
            }
        } 
         catch(Exception e) 
         {
           System.err.println(e.getMessage());
           clients.remove(this);
           users.remove(name);
         }
    }
  }
}
  • Try putting `scanner.netLine();` just before `name = scanner.nextLine();` and see if it works fine. – Smit Dec 02 '13 at 22:58

1 Answers1

0

After this line:

Socket cs = new Socket( scanner.next(), scanner.nextInt() ); 

add:

scanner.nextLine();

So together, it would look like:

Socket cs = new Socket( scanner.next(), scanner.nextInt() ); 
scanner.nextLine();

This is done to swallow the dangling end of line (EOL) token that is not handled by next() or nextInt() and in fact is only handled by nextLine().

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373