Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Help Please - Not sure why i can't get them to work at all!

  1. #1
    Junior Member
    Join Date
    Apr 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help Please - Not sure why i can't get them to work at all!

    Im going to attach my 3 programs here which they are actually interlinked, The ClientServerSession is actually one that is running the leg work, the ClientOnServer is the user interface that shows up but actually its the ClientServerSession that is running, the user basically inputs his name, and in the event if he sends a message, the message is suppose to go thru and then message gets accepted into ClassOnServer which ClassOnServer will activate the sendToAll() and broadcast it to every client that is connected. Here are the codes.

    ClassOnServer
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    public class ClassOnServer
    {
        public static final int portNumber = 5000;
        private ArrayList<Socket> clientList;
        Socket aSock = new Socket();
        ClassOnServer aConsultant;
        Writer out;
     
        public static void main(String [] args)
        {
            try
            {   
                ClassOnServer consultant = new ClassOnServer();
            }
            catch (IOException e) {System.out.println(e);}
        }
     
        public ClassOnServer() throws IOException
        {
            // Listen for client connections on portNumber
            ServerSocket serverlistener = new ServerSocket(portNumber);
            System.out.println("Ready for client requests");
            int i=1;
     
            //Infinite loop
            while(true)
            {
                //Waiting for connection to come in
                Socket sSock = serverlistener.accept();
                System.out.println("Client " + i + " accepted");
                //Create a Socket object that represents a new client server session
                //Thread session = new ClientServerSession(i, sSock.getInputStream(), sSock.getOutputStream());
                Thread session = new ClientServerSession(i, aConsultant, aSock);
                //Start session         
                session.start();
                i++;
            }
        }
     
        public void removeConnection(Socket s)
        {
            for (int i = 0; i < clientList.size(); i++)
            {
                if (s.equals(clientList.get(i)))
                {
                    clientList.remove(s);
                }
           }
        }
     
        public synchronized void sentToAll(String message, String name)
        {
            for (int i=0; i < clientList.size(); i++)
            {   
                try 
                {
                    Socket s = (Socket)clientList.get(i);
                    out =  new OutputStreamWriter(s.getOutputStream());
                    out.write("Sent by client " + name + ":" + message + "\n");
                    out.flush();
                }
                catch (IOException ex) { }
            }
        }
    }

    ClassOnClient:
    import java.io.*;
    import java.net.*;
    public class ClassOnClient
    {
    	public static final int portNumber = 5000;
    	BufferedReader input, userTerminal;
    	Writer output;
    	ObjectOutputStream out;
     
    	public static void main(String [] args)
    	{
    		try
    		{	
    		    ClassOnClient clientObject = new ClassOnClient();
    		}
    		catch (IOException e) {System.out.println(e);}
    	}
     
    	public ClassOnClient() throws IOException
    	{
    		Socket cSock = new Socket("LocalHost", portNumber);
    		Reader iRead = new InputStreamReader(cSock.getInputStream());
    		input = new BufferedReader(iRead);
    		userTerminal = new BufferedReader(new InputStreamReader(System.in));
    		output = new OutputStreamWriter(cSock.getOutputStream());
    		while(true)
    		{
    			String line = input.readLine();
    			System.out.println (line);
    			line = userTerminal.readLine();
    			if (line.equals("q")) break;
    			output.write(line + "\n");
    			output.flush();
    		}
    		System.out.println("Disconnected with Server");
    	}
    }

    ClientServerSession:
    import java.io.*;
    import java.net.*;
    public class ClientServerSession extends Thread
    {
        private String username;
        private String message;
        BufferedReader in, userTerminal;
        Writer out, output;
        int id;
        ClassOnServer server;
     
        public ClientServerSession (int id, ClassOnServer server, Socket sSock) throws IOException
        {
            this.id = id;
            this.server = server;
     
            //sSock = new Socket("LocalHost", 5000);
            Reader iRead = new InputStreamReader(sSock.getInputStream());
            in = new BufferedReader(iRead);
            userTerminal = new BufferedReader(new InputStreamReader(System.in));
            output = new OutputStreamWriter(sSock.getOutputStream());
     
            //InputStream inS;
            //OutputStream outS;
            //Reader iRead = new InputStreamReader(inS);
            //out = new OutputStreamWriter(outS);
     
        }
     
        public void run()
        {
            try
            {   
                output.write("Enter your name: \n");
                output.flush();
                while (true)
                {
     
                    //--Displays user name and prompts for an initial message
                    username = userTerminal.readLine();
                    String name = username;
                    output.write(name + ", please enter a message:(q to end) \n");
                    output.flush();
     
                    while(true)
                    {
                        //--Displays user name and message
                        message = userTerminal.readLine();
                        String msg = message;
                        output.write(name + ": " + message);
                        output.flush();
                    }
                }
            }
            catch (IOException e) 
            {
                System.out.println(e);
            }
        }
    }

    ClassOnClient is 100% accurate, might need some tweaking in ClassOnServer, however im sure the big chunk of why this isn't working lies with the ClientServerSession.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Help Please - Not sure why i can't get them to work at all!

    this isn't working
    Can you explain what the problem is? What does the code do or not do?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Apr 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help Please - Not sure why i can't get them to work at all!

    This program im trying to create a client-server program chat that allows the server to send all text received from any of the connected clients to all clients. This means that the server has to receive and send, and the client has to send as well as receive.

    For each invididual class:
    ClassOnServer: listens out for incoming connections, and has the following methods in it
    A constructor that
     Listens for client connections on portNumber
     Creates an infinite loop that
    i. Waits for a connection to come in.
    ii. When a new connection comes in, create a Socket object that represents a new client server session and starts the session – see ClientServerSession class below.
    iii. Adds the Socket object to the ArrayList.
    b. sendToAll() method with parameters a String message and a String name that loops through the ArrayList and sends to each Socket object the following message:
    “Sent by Client ” + name + “: ” + message
    c. removeConnection() method with parameter Socket s that removes s from the ArrayList when the connection has closed so that the server does not waste time sending messages to clients that are no longer connected.

    ClassOnClient
    ClassOnClient class: This class models the behaviour of the client and has a constructor that
     Creates a new Socket object that will send to portNumber
     Creates an input and an output stream with the Socket object.
     Creates an input stream that reads from the keyboard
     Creates a loop that
    i. Read an incoming message
    ii. Prints it on the screen
    iii. Reads user response
    iv. If user response is “q”, end the loop
    v. Otherwise write user response back to the server

    ClientServerSession class: This Thread subclass handles each client connection and has the following methods:
    a. A constructor with three parameters: an integer representing the id of the client, a ClassOnServer object and a Socket object. The constructor is responsible to create the input and output streams to the Socket object.
    b. A run() method that
    a. Asks user for his name
    b. Creates an infinite loop that
    i. Asks for a message
    ii. If the message is not empty, use the ClassOnServer sendToAll() method to broadcast to all clients.
    c. When the client disconnects, remove the client from the server.

    Currently, whenever i connect up the server and attempt to connect a client to it, it immediately gets disconnected, however, there is a message displayed showing no connection to the client, which means that there could be a message that triggered the sendToAll() Method, but currently im not sure why my clients are getting disconnected the moment they connect on.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Help Please - Not sure why i can't get them to work at all!

    Try debugging the code by adding lots of println statements that print messages as the code executes to show where the code executes and the values of all the variables involved.

    How do you test the code?
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Why does this work?
    By Skybear in forum What's Wrong With My Code?
    Replies: 5
    Last Post: December 16th, 2012, 01:23 AM
  2. how does this work?
    By somebodyonearth in forum Java Theory & Questions
    Replies: 3
    Last Post: March 10th, 2012, 01:23 PM
  3. Does this work?
    By marmanq in forum What's Wrong With My Code?
    Replies: 17
    Last Post: February 20th, 2012, 10:51 AM
  4. I cant work it out!!!
    By tuts73 in forum What's Wrong With My Code?
    Replies: 25
    Last Post: January 18th, 2012, 10:16 AM
  5. Do you work out?
    By thesolo in forum Totally Off Topic
    Replies: 4
    Last Post: October 24th, 2011, 08:03 AM