View Single Post
  #1 (permalink)  
Old 08-30-2008, 10:04 PM
christuart christuart is offline
Member
 
Join Date: Aug 2008
Location: UK
Posts: 6
Rep Power: 0
christuart is on a distinguished road
Default [SOLVED] Cant compare strings sent by client
I am writing a small chat client to try to learn networking with Java (and Java in general). I have written a server which works absolutely fine when connected to with Telnet on linux. However, when messages are sent from the client I have written, the server cannot interpret the commands and outputs them as normal messages.

My apologies for the large amount of code I'm posting!

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

class Server
{
  public static final int PORT = 9988;
  public static final int MAX_CLIENTS = 3;
  public int connectedClients = 0;
  private ClientHandler[] clients = new ClientHandler[MAX_CLIENTS];
  public Server()
  {
    try
    {
      ServerSocket socket = new ServerSocket(PORT);
      System.out.println("Server started.");
      while (true)
      {
        if (connectedClients<MAX_CLIENTS)
        {
          Short a=0;
          while (clients[a]!=null)
          {
            a++;
          }
          clients[a] = new ClientHandler(socket.accept(),a,this);
          connectedClients++;
          System.out.println("Client connected. Current clients: "+connectedClients);
          clients[a].start();
        }
        else
        {
          Socket extraClient = socket.accept();
          DataOutputStream output = new DataOutputStream(extraClient.getOutputStream());
          output.writeChars("Sorry, server is full. Try again later.\n");
          extraClient.close();
        }
      }
    }
    catch(IOException error)
    {
      System.out.println("Oops! Error while starting server");
    }
  }

  public static void main(String args[])
  {
    Server server = new Server();
    while (true);
  }

  public void clientClosing(Short index)
  {
    String leaver = clients[index].name;
    clients[index] = null;
    connectedClients--;
    System.out.println("Client disconnected. Current clients: "+connectedClients);
    sayAll("*** "+leaver+" has left.");
  }

  public void sayAll(String message)
  {
    for(Short a=0;a<MAX_CLIENTS;a++)
    {
      if (clients[a]!=null)
      {
        clients[a].say(message+"\n");
      }
    }
    System.out.println("Message sent to all: "+message);
  }

  public void sayOne(String name, String message, short from)
  {
    boolean foundClient=false;
    for (short a=0;a<MAX_CLIENTS;a++)
    {
      if (clients[a]!=null)
      {
        if (clients[a].name.equalsIgnoreCase(name))
        {
          clients[a].say(message+"\n");
          System.out.println("Message sent to "+clients[a]+": "+message);
          foundClient = true;
          break;
        }
      }
    }
    if (!foundClient)
    {
      clients[from].say("Message not sent: "+message+"\nName not found: "+name+".\n");
    }
  }

  public boolean getNameTaken(String checking, short clientIndex)
  {
    boolean toReturn = false;
    for (short a = 0; a<MAX_CLIENTS; a++)
    {
      if (a!=clientIndex&&clients[a] != null)
      {
        if (clients[a].name!=null)
        {
          if (clients[a].name.equals(checking))
          {
            toReturn = true;
            break;
          }
        }
      }
    }
    return toReturn;
  }

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

class ClientHandler extends java.lang.Thread
{
  Socket client;
  Short index;
  Server host;
  DataOutputStream output;
  BufferedReader input;
  String name = null;
  boolean running = true;

  short helpLength = 6;
  String[] help = new String[]
                        {"*** Help for the messaging thing.\n***\n",
                         "*** To quit, type '/#quit'\n",
                         "*** To change your name, type '/#name <new_name>'.\n",
                         "*** To send a private message, type '/#pm <recipient> <message>'.\n",
                         "*** Otherwise, simply type your message and press enter!\n***\n***\n***\n",
                         "*** You just lost the game!\n\n"};

  short welcomeLength = 2;
  String[] welcome = new String[]
                           {"*** Boo! You have connected. How amaxing!\n",
                            "*** Please identify yourself.\n"};

  public ClientHandler(Socket handlee, Short arrayIndex, Server host)
  {
    client = handlee;
    index = arrayIndex;
    this.host = host;
    try
    {
      output = new DataOutputStream(client.getOutputStream());
    }
    catch (IOException error)
    {
      System.out.println("Failed to get output stream for client "+index);
    }

    try
    {
      input = new BufferedReader(new InputStreamReader(client.getInputStream()));
    }
    catch (IOException error)
    {
      System.out.println("Failed to get input stream for client "+index);
    }
  }

  public void run()
  {
    if (running)
    {
      try
      {
        for (int a=0;a<welcomeLength;a++)
        {
          output.writeChars(welcome[a]);
        }
      }
      catch(IOException error)
      {
        System.out.println("Oops! Error sending welcome message.");
      }
      giveName();
      host.sayAll("*** "+name+" has joined.");
      System.out.println("Client "+index+" is called "+name);
      while (running)
      {
        String receivedMessage=null;
        try
        {
          receivedMessage = input.readLine();
        }
        catch (IOException error)
        {
          System.out.println("Error while receiving message.");
        }
        try
        {
          if (receivedMessage!=null)
          {
            if (receivedMessage.trim().equalsIgnoreCase("/#quit"))
            {
              output.writeChars("*** You are leaving the chat.\n");
              quit();
            }
            else if (receivedMessage.trim().equalsIgnoreCase("/#help"))
            {
              for (int a=0;a<helpLength;a++)
              {
                output.writeChars(help[a]);
              }
            }
            else if (receivedMessage.toLowerCase().startsWith("/#pm"))
            {
              String[] splitMessage = receivedMessage.split(" ",3);
              if (splitMessage.length==3)
              {
                host.sayOne(splitMessage[1],"<from "+name+"> "+splitMessage[2],index);
              }
              else
              {
                output.writeChars("*** Please follow the correct format of '/#pm <recipient> <message>'.\n");
              }
            }
            else if (receivedMessage.toLowerCase().startsWith("/#name"))
            {
              System.out.println("receivedMessage="+receivedMessage);
              receivedMessage+=" ";
              System.out.println("now receivedMessage="+receivedMessage);
              String[] splitMessage = receivedMessage.split(" ",2);
              System.out.println("splitMessage[0]="+splitMessage[0]);
              System.out.println("splitMessage[1]="+splitMessage[1]);
              resetName(splitMessage[1]);
            }
            else
            {
              if (receivedMessage.equalsIgnoreCase("help")||receivedMessage.equalsIgnoreCase("/help"))
              {
                output.writeChars("*** For help type '/#help'\n");
              }
              host.sayAll("<"+name+"> "+receivedMessage);
            }
          }
        }
        catch (IOException error)
        {
          System.out.println("Error while reacting after receiving message from client "+index);
        }
      }
    }
  }

  public void quit()
  {
    try
    {
      stopThread();
      input.close();
      output.close();
      client.close();
    }
    catch(IOException error)
    {
      System.out.println("Error while closing (input stream, output stream or client socket for) client "+index);
    }
    host.clientClosing(index);
  }

  public void giveName()
  {
    try
    {
      while (name == null)
      {
        name = input.readLine();
      }
      if (name.equals(name.split(" ")[0]))
      {
        if (host.getNameTaken(name,index))
        {
          output.writeChars("*** That name is taken. Please enter another.\n");
          name = null;
          giveName();
        }
        else
        {
          output.writeChars("*** Name accepted. To change your name type '/#name <new_name>'.\n");
        }
      }
      else
      {
        output.writeChars("*** That name is invalid. Remember: spaces are not allowed.\n");
        giveName();
      }
    }
    catch (IOException error)
    {
      System.out.println("Error while setting name for client "+index);
    }
  }

  public void resetName(String newName)
  {
    try
    {
      String[] splittedNewName = newName.split(" ");
      if (newName.trim()!=null && newName.trim()!="" && newName!="")
      {
        if (newName.trim().equals(splittedNewName[0]))
        {
          newName = newName.trim();
          if (host.getNameTaken(name,index))
          {
            output.writeChars("*** That name is taken. Please enter another.\n");
          }
          else
          {
            output.writeChars("*** New name accepted.\n");
            System.out.println("Client "+index+" ("+name+") is now called "+newName);
            name = newName;
          }
        }
        else
        {
          output.writeChars("*** That name is invalid. Remember: spaces are not allowed.\n");
        }
      }
    }
    catch (IOException error)
    {
      System.out.println("Error while resetting name for client "+index);
    }
  }
  
  public void say(String message)
  {
    try
    {
      output.writeChars(message);
    }
    catch (IOException error)
    {
      System.out.println("Error while sending message to client "+index);
    }
  }

  public void stopThread()
  {
    running = false;
  }

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

class Client
{
  
  Socket socket;
  public static String SERVER_NAME;
  public static int SERVER_PORT;
  public static String habladora;
  ClientSender sender;
  ClientReceiver receiver;


  public Client(String name, int port, String nick)
  {

    SERVER_NAME = name;
    SERVER_PORT = port;
    habladora = nick;

    try
    {
      socket = new Socket(SERVER_NAME,SERVER_PORT);
    }
    catch(UnknownHostException error)
    {
      System.out.println("Could not connect to server "+SERVER_NAME+":"+SERVER_PORT+" (a)");
    }
    catch(IOException error)
    {
      System.out.println("Could not connect to server "+SERVER_NAME+":"+SERVER_PORT+" (b)");
    }

    sender = new ClientSender(socket, habladora);
    receiver = new ClientReceiver(socket);
    sender.start();
    receiver.start();

  }

  public static void main(String[] args)
  {

    Client client;
    if (args.length == 3)
    {
      client = new Client(args[0],Integer.valueOf(args[1]),args[2]);
    }
    else
    {
      client = new Client("localhost",9988,"Chris");
    }
    while(true);
  }


  public void closeClient()
  {

    try
    {
      socket.close();
      sender.stopThread();
      receiver.stopThread();
    }
    catch(IOException error)
    {
      System.out.println("Could not close socket for server.");
    }

  }

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

class ClientSender extends Thread
{

  Socket server;
  BufferedReader inStream;
  boolean running = true;
  DataOutputStream output;
  String habladora;

  public ClientSender(Socket server, String name)
  {

    this.server = server;
    habladora = name;

    try
    {
      output = new DataOutputStream(server.getOutputStream());
    }
    catch (IOException error)
    {
      System.out.println("Failed to get output stream for server.");
    }

    try
    {
      output.writeChars(habladora+"\n");
    }
    catch(IOException error)
    {
      System.out.println("Error while giving name to server.");
    }

    inStream = new BufferedReader ( new InputStreamReader(System.in) );

  }

  public void run()
  {

    System.out.println("Sender thread started.");
    while (running)
    {
  
      String inMessage="";
      try
      {
        inMessage = inStream.readLine();
        if(!inMessage.trim().equals(""))
        {
          if (inMessage.equals("/#quit"))
          {
            output.writeChars("/#quit\n");
            System.out.println("Attempting quit.");
          }
          else
          {
            output.writeChars(inMessage+"\n");
          }
        }
      }
      catch(IOException error)
      {
        System.out.println("Error while inputting or sending message");
      }
  
    }

  }

  public void stopThread()
  {
    running = false;
  }

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

class ClientReceiver extends Thread
{

  Socket server;
  BufferedReader input;
  boolean running = true;

  public ClientReceiver(Socket server)
  {
    this.server = server;
  }

  public void run()
  {

    System.out.println("Receiver thread started.");
    try
    {
      input = new BufferedReader(new InputStreamReader(server.getInputStream()));
    }
    catch (IOException error)
    {
      System.out.println("Failed to get input stream for server.");
    }

    while(running)
    {
      String receivedMessage=null;
      try
      {
        receivedMessage = input.readLine();
      }
      catch (IOException error)
      {
        System.out.println("Error while receiving message.");
      }
      if(receivedMessage!=null)
      {
        System.out.println(receivedMessage);
      }
    }
  }

  public void stopThread()
  {
    running = false;
  }

}
Can anyone shed light on what the problem might be?

Thanks,
Chris.
__________________
There's no place like 127.0.0.1

Last edited by christuart; 08-31-2008 at 01:49 PM.
Reply With Quote