6 Replies - 1356 Views - Last Post: 28 March 2011 - 02:18 PM Rate Topic: -----

#1 mjwilson1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 09-February 11

Sending name of client to server and server repeats it back.

Posted 26 March 2011 - 09:24 AM

I'm trying to create a client/server program that when the client connects, they enter their name and it sends it to the server. The server stores the names in an ArrayList and waits until 5 clients have joined and enter their names. The server then repeats back the five names to the five clients connected.

At the minute multiple clients can connect to the server however when they are asked to enter their name it then re-asks them to enter their name instead of displaying 'Name Accepted!" and storing it in the arraylist. I have tried searching for client/server chat applications to try and get the concept of how the server handles the data however this not a chat program so it didn't help much. Also, please keep explanations simple as I'm still really only getting to learn java and don't understand when someone come across too technical. I would appreciate any help anyone could give me through adding code or taking code out to help me get this working. Thanks in advance.

Code for FTMultiServer (server)

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

class FTMultiServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        boolean listening = true;
        int num_people = 0;

        try {
            serverSocket = new ServerSocket(8888);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + 8888 + ", " + e.getMessage());
            System.exit(1);
        }

       
         while (listening) {
            Socket clientSocket = null;
            //while (num_people < 5) {
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                System.err.println("Accept failed: " + 8888 + ", " + e.getMessage());
                continue;
            }
            //}
            new FTMultiServerThread(clientSocket).start();
            num_people = num_people +1;
            System.out.println(num_people);
        }

        try {
            serverSocket.close();
        } catch (IOException e) {
            System.err.println("Could not close server socket." + e.getMessage());
        }
    }
}



Code for FTMultiServerThread (Server Helper)

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

class FTMultiServerThread extends Thread {
    Socket socket = null;

    FTMultiServerThread(Socket socket) {
        super("FTMultiServerThread");
        this.socket = socket;
    }
int namecount = 5;
private static BufferedReader fullName = new BufferedReader( new InputStreamReader( System.in ));
    public void run() {

        try {
           
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter os = new PrintWriter(new OutputStreamWriter(socket.getOutputStream() ) );
            PrintWriter ns = new PrintWriter(new OutputStreamWriter(socket.getOutputStream() ) );
            
            FTStates fts = new FTStates();
            FTStates fta = new FTStates();
            String inputLine, outputLine, fullName;
            
            
            outputLine = fts.processInput(null);
            fullName = fta.processInput(null);
            os.println(outputLine);
            ns.println(fullName);
            os.flush();
            ns.flush();
            
               
            
            
            while ((inputLine = is.readLine()) != null) {

               //outputLine = fts.processInput(inputLine);
               //os.println(outputLine);
               ns.println(fullName);
               os.flush();
               ns.flush();
            if (outputLine.equals("Name Accepted!"));
                   ArrayList al = new ArrayList(); 
                   for(int i = 0; i < 5; i++)
                   al.add(fullName);            
               if (outputLine.equals("Bye."))
                    break;
            }
            os.close();
            is.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




Code for FTStates (Server communication with the clients)


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

class FTStates {
    private static final int WAITING = 0;
    private static final int SENTNAMEREQUEST = 1;
    
    private int state = WAITING;
    String[] roseindia={};
    

    String processInput(String theInput) {
        
        String fullName = "";       
        String theOutput = null;
        if (state == WAITING) {
            theOutput = "Enter Name:";
            state = SENTNAMEREQUEST;
        } else if (state == SENTNAMEREQUEST) {
            if (theInput.equalsIgnoreCase("")) {
                theOutput = "You Must Enter a Name:";
            } else {
                theOutput = "Name Accepted!";
                //while (num_mem < 5);
                state = WAITING;
                return fullName;
                }
        }
        return theOutput;
        //return num_mem;
    }
}




The code for the client is fairly basic. It's really just the server side I need help with in handling the input/output to and from the clients.

View Postmjwilson1, on 26 March 2011 - 09:21 AM, said:

I'm trying to create a client/server program that when the client connects, they enter their name and it sends it to the server. The server stores the names in an ArrayList and waits until 5 clients have joined and enter their names. The server then repeats back the five names to the five clients connected.

At the minute multiple clients can connect to the server however when they are asked to enter their name it then re-asks them to enter their name instead of displaying 'Name Accepted!" and storing it in the arraylist. I have tried searching for client/server chat applications to try and get the concept of how the server handles the data however this not a chat program so it didn't help much. Also, please keep explanations simple as I'm still really only getting to learn java and don't understand when someone come across too technical. I would appreciate any help anyone could give me through adding code or taking code out to help me get this working. Thanks in advance.

Code for FTMultiServer (server)

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

class FTMultiServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        boolean listening = true;
        int num_people = 0;

        try {
            serverSocket = new ServerSocket(8888);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + 8888 + ", " + e.getMessage());
            System.exit(1);
        }

       
         while (listening) {
            Socket clientSocket = null;
            //while (num_people < 5) {
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                System.err.println("Accept failed: " + 8888 + ", " + e.getMessage());
                continue;
            }
            //}
            new FTMultiServerThread(clientSocket).start();
            num_people = num_people +1;
            System.out.println(num_people);
        }

        try {
            serverSocket.close();
        } catch (IOException e) {
            System.err.println("Could not close server socket." + e.getMessage());
        }
    }
}



Code for FTMultiServerThread (Server Helper)

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

class FTMultiServerThread extends Thread {
    Socket socket = null;

    FTMultiServerThread(Socket socket) {
        super("FTMultiServerThread");
        this.socket = socket;
    }
int namecount = 5;
private static BufferedReader fullName = new BufferedReader( new InputStreamReader( System.in ));
    public void run() {

        try {
           
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter os = new PrintWriter(new OutputStreamWriter(socket.getOutputStream() ) );
            PrintWriter ns = new PrintWriter(new OutputStreamWriter(socket.getOutputStream() ) );
            
            FTStates fts = new FTStates();
            FTStates fta = new FTStates();
            String inputLine, outputLine, fullName;
            
            
            outputLine = fts.processInput(null);
            fullName = fta.processInput(null);
            os.println(outputLine);
            ns.println(fullName);
            os.flush();
            ns.flush();
            
               
            
            
            while ((inputLine = is.readLine()) != null) {

               //outputLine = fts.processInput(inputLine);
               //os.println(outputLine);
               ns.println(fullName);
               os.flush();
               ns.flush();
            if (outputLine.equals("Name Accepted!"));
                   ArrayList al = new ArrayList(); 
                   for(int i = 0; i < 5; i++)
                   al.add(fullName);            
               if (outputLine.equals("Bye."))
                    break;
            }
            os.close();
            is.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




Code for FTStates (Server communication with the clients)


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

class FTStates {
    private static final int WAITING = 0;
    private static final int SENTNAMEREQUEST = 1;
    
    private int state = WAITING;
    String[] roseindia={};
    

    String processInput(String theInput) {
        
        String fullName = "";       
        String theOutput = null;
        if (state == WAITING) {
            theOutput = "Enter Name:";
            state = SENTNAMEREQUEST;
        } else if (state == SENTNAMEREQUEST) {
            if (theInput.equalsIgnoreCase("")) {
                theOutput = "You Must Enter a Name:";
            } else {
                theOutput = "Name Accepted!";
                //while (num_mem < 5);
                state = WAITING;
                return fullName;
                }
        }
        return theOutput;
        //return num_mem;
    }
}




The code for the client is fairly basic. It's really just the server side I need help with in handling the input/output to and from the clients.


On second thoughts, maybe it'd be better I posted the client code as well.

Code for FTClient (Client)


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

public class FTClient {
    public static void main(String[] args) {
        Socket ftSocket = null;
        PrintWriter os = null;
        BufferedReader is = null;

        try {
            ftSocket = new Socket("localhost", 8888);
            os = new PrintWriter( new OutputStreamWriter(ftSocket.getOutputStream()));
            is = new BufferedReader( new InputStreamReader(ftSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: localhost");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: localhost");
        }

        if (ftSocket != null && os != null && is != null) {
            try {
                StringBuffer buf = new StringBuffer(50);
                int c;
                String fromServer;
                String input = null;

                while ((fromServer = is.readLine()) != null) {
                    System.out.println("Server: " + fromServer);
                    if (fromServer.equals("Bye."))
                        break;
	 // sets up astream for user input 
                    BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in));    
                    input = userInput.readLine();  
                    System.out.println("Client: " + input);
                    os.println(input);
                    os.flush();
                }
                os.close();
                is.close();
                ftSocket.close();
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Sending name of client to server and server repeats it back.

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,912
  • Joined: 06-March 08

Re: Sending name of client to server and server repeats it back.

Posted 26 March 2011 - 08:09 PM

while (listening) {

where do you change the value of listening ?
Was This Post Helpful? 1
  • +
  • -

#3 mjwilson1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 09-February 11

Re: Sending name of client to server and server repeats it back.

Posted 27 March 2011 - 01:03 PM

While listening, the server accepts connections form clients i.e. clientSocket = serverSocket.accept(); and creates a new thread for each i.e. new FTMultiServerThread(clientSocket).start(); Each thread is handled by FTMultiServerThread
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,912
  • Joined: 06-March 08

Re: Sending name of client to server and server repeats it back.

Posted 27 March 2011 - 01:43 PM

so you mean that

while(listening) {

can be replace by

while(true)

it is just an infinite loop
Was This Post Helpful? 1
  • +
  • -

#5 mjwilson1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 09-February 11

Re: Sending name of client to server and server repeats it back.

Posted 28 March 2011 - 01:21 AM

Exactly. Yeah, it would be the same as saying 'while listening = true'.
Was This Post Helpful? 0
  • +
  • -

#6 Greltam  Icon User is offline

  • D.I.C Head

Reputation: 90
  • View blog
  • Posts: 225
  • Joined: 29-January 09

Re: Sending name of client to server and server repeats it back.

Posted 28 March 2011 - 06:44 AM

Not sure if this is a problem, but in your FTMultiServerThread while ((inputLine = is.readLine()) != null) loop, you mean to have it keep reading in the names from clients, however I believe the loop is terminating shortly after instantiated because is's buffer probably isn't filled with all client names at once. try sticking it in an infinite loop?

This post has been edited by Greltam: 28 March 2011 - 06:48 AM

Was This Post Helpful? 0
  • +
  • -

#7 mjwilson1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 09-February 11

Re: Sending name of client to server and server repeats it back.

Posted 28 March 2011 - 02:18 PM

yeah, i know what you mean, i've changed this now to while (true);
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1