Results 1 to 11 of 11
  1. #1
    sari's Avatar
    sari is offline Member
    Join Date
    Jan 2009
    Posts
    32
    Rep Power
    0

    Default Am I doing it horribly wrong?

    My goal was to create a very simple message passing server program, just to experiment with Client-Server, sockets and all that. While I know this code has a lot of flaws, downfalls, etc... I don't see why it won't pass a message from one client to the other. If you look down to the class "Client" and go to the run() function you'll even see that I've added a line to send out on connection... that line never gets through to the client(I am using telnet, by the way.) If anyone could explain this to me and what I've done wrong here to make it so it won't function, that would be really, really awesome.

    Thanks in advance,

    Sari

    Java Code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    /**
     *
     * @author Keith
     */
    public class KChatServer {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws Exception {
            
            BufferedReader cmdIn = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Welcome to KChat, server version.");
            System.out.println("\nPlease enter your enter the password for your server"
                    + ", if there is no password, leave blank.");
            
            System.out.println("Select a Server PW: ");
            String pw = cmdIn.readLine();
            
            System.out.println("Select Operational Port: ");
            int port = Integer.parseInt(cmdIn.readLine());
            
            ServerSocket sock = new ServerSocket(port);
            
            ClientManager cm = new ClientManager();
            
            cm.run();
            
            while (true) {
                try {
                    cm.addClient(new Client(sock.accept()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
        }
    }
    
    class ClientManager
        extends Thread {
        
        Vector<Client> cls = new Vector(100);
        
        public ClientManager() { }
        
        public void addClient(Client c) {
            c.run();
            cls.add(c);
        }
        
        public void run() {
            int cnt = 1;
            Client cc;
            
            while (true) {
                try {
                    cc = cls.get(cnt);
                } catch (Exception ob) {
                    cc = null;
                }
                
                if (cc != null) {
                    if (cc.content.toString() != null) {
                        sendContent(cc.content.toString());
                        cc.content = new StringBuffer();
                    }
                
                    cnt++;
                    if (cnt >= cls.size()) {
                        cnt = 1;
                    }
                }
            }
        }
        
        public void sendContent(String cont) {
            int len = cls.size();
            int cnt = 0;
            
            while (cnt < len) {
                cls.get(cnt).sending.append(cont);
                System.out.println(cls.get(cnt).content);
                cnt++;
            }
        }
    }
    
    class Client
        extends Thread {
    
        
        Socket connsock;
        PrintWriter out;
        BufferedReader in;
        StringBuffer content;
        StringBuffer sending;
        boolean quit = false;
        
        public Client(Socket s) {
            connsock = s;
            try {
                in = new BufferedReader(new InputStreamReader(connsock.getInputStream()));
                out = new PrintWriter(s.getOutputStream());
                System.out.println("Client connected: " + connsock.getInetAddress().getHostAddress());
                content = new StringBuffer();
                sending = new StringBuffer();
                        
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        public void run() {        
            out.println("Server hub: We started your thread there, pal :)");
            while (true) {
                try {
                    String tmp = in.readLine();
                    if (tmp != null) {
                        content.append(tmp);
                    }
                    
                    if (sending.toString() != null) {
                        out.println(sending.toString());
                        sending = new StringBuffer();
                        
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    quit = true;
                }
             }
        }
    }
    If you don't try you can't succeed.

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Am I doing it horribly wrong?

    Try flushing the stream after you write.
    Get in the habit of using standard Java naming conventions!

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Am I doing it horribly wrong?

    The readLine waits for the end of the line. Are you sending an endline (\n)?

    Add more debugging printlns so you can see exactly where the code is hanging.
    You should post the console with the print outs that shows what the program did when you executed it.

  4. #4
    sari's Avatar
    sari is offline Member
    Join Date
    Jan 2009
    Posts
    32
    Rep Power
    0

    Default Re: Am I doing it horribly wrong?

    Alright guys, thank you for your replies it's very much appreciated.

    I've tried flushing my PrintWriters after connection and added another debug line that's supposed to be sent on connection.

    I've revised the code to the following:

    Java Code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    /**
     *
     * @author Keith
     */
    public class KChatServer {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws Exception {
            
            
            PrintWriter out = null;
            BufferedReader cmdIn = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Welcome to KChat, server version.");
            System.out.println("\nPlease enter your enter the password for your server"
                    + ", if there is no password, leave blank.");
            
            System.out.println("Select a Server PW: ");
            String pw = cmdIn.readLine();
            
            System.out.println("Select Operational Port: ");
            int port = Integer.parseInt(cmdIn.readLine());
            
            ServerSocket sock = new ServerSocket(port);
            
            ClientManager cm = new ClientManager();
            
            cm.run();
            
            while (true) {
                try {
                    Socket s = sock.accept();
                    out = new PrintWriter(s.getOutputStream());
                    out.print("--Connection accepter--");
                    out.flush();
                    cm.addClient(new Client(s));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
        }
    }
    
    class ClientManager
        extends Thread {
        
        Vector<Client> cls = new Vector(100);
        
        public ClientManager() { }
        
        public void addClient(Client c) {
            c.run();
            cls.add(c);
        }
        
        public void run() {
            int cnt = 1;
            Client cc;
            
            while (true) {
                try {
                    cc = cls.get(cnt);
                } catch (Exception ob) {
                    cc = null;
                }
                
                if (cc != null) {
                    if (cc.content.toString() != null) {
                        sendContent(cc.content.toString());
                        cc.content = new StringBuffer();
                    }
                
                    cnt++;
                    if (cnt >= cls.size()) {
                        cnt = 1;
                    }
                }
            }
        }
        
        public void sendContent(String cont) {
            int len = cls.size();
            int cnt = 0;
            
            while (cnt < len) {
                cls.get(cnt).sending.append(cont);
                System.out.println(cls.get(cnt).content);
                cnt++;
            }
        }
    }
    
    class Client
        extends Thread {
    
        
        Socket connsock;
        PrintWriter out;
        BufferedReader in;
        StringBuffer content;
        StringBuffer sending;
        boolean quit = false;
        
        public Client(Socket s) {
            connsock = s;
            try {
                in = new BufferedReader(new InputStreamReader(connsock.getInputStream()));
                out = new PrintWriter(s.getOutputStream());
                System.out.println("Client connected: " + connsock.getInetAddress().getHostAddress());
                content = new StringBuffer();
                sending = new StringBuffer();
                        
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        public void run() {        
            out.println("Server hub: We started your thread there, pal :)");
            out.flush();
            while (true) {
                try {
                    String tmp = in.readLine();
                    if (tmp != null) {
                        content.append(tmp + "\n");
                    }
                    
                    if (sending.toString() != null) {
                        out.println(sending.toString());
                        out.flush();
                        sending = new StringBuffer();
                        
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    quit = true;
                }
             }
        }
    }
    Edit: I'm assuming telnet is sending newlines, though I should probably test it... will do when I get home.
    Last edited by sari; 12-02-2011 at 05:52 PM.
    If you don't try you can't succeed.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Am I doing it horribly wrong?

    Does it work now? If not please explain and post the contents of the console showing the print outs.

  6. #6
    sari's Avatar
    sari is offline Member
    Join Date
    Jan 2009
    Posts
    32
    Rep Power
    0

    Default Re: Am I doing it horribly wrong?

    Alright, so I know that the server is accepting the connection because otherwise telnet wouldn't move onto the input/output screen. When I try to send something through telnet, the connection doesn't do anything, additionally, the line it's supposed to be sending on connection isn't working either. I tried testing telnet to make sure it's sending it's data properly with "telnet google.com 80" and then typing "GET /"... telnet is not the issue. It seems to me that my connections just aren't sending anything. The server isn't getting data from the clients and the server isn't sending anything. To clarify... I don't think this is the issue, but I'm testing all the clients and the server from one machine I.E. the same IP adress... though I'm connecting using "telnet localhost <port>" so I'm very unsure of what's going on here.

    P.S. So the console I/O there isn't anything to show, because no data gets received on either end.

    Sari
    If you don't try you can't succeed.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Am I doing it horribly wrong?

    Strange that there is nothing on the console. In see printlns in your code. If they do not print, then your code must not be executing at all.

  8. #8
    sari's Avatar
    sari is offline Member
    Join Date
    Jan 2009
    Posts
    32
    Rep Power
    0

    Default Re: Am I doing it horribly wrong?

    There must be something wrong with my logic then, and I've looked over it a thousand times(not literally) and I can't figure it out.
    If you don't try you can't succeed.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Am I doing it horribly wrong?

    There must be something wrong with my logic
    Yes there is something wrong with it.
    You need to debug your code to see what the problem is.
    Add lots of printlns to show where the execution flow goes and what the values of the variables are as they are changed.
    The print out will show where a problem is.

  10. #10
    mozly is offline Member
    Join Date
    Dec 2011
    Posts
    4
    Rep Power
    0

    Default Re: Am I doing it horribly wrong?

    I had this problem before. It is because buffered reader blocks the thread until there is a line to be read
    on line 122 add an if statement like so:

    Java Code:
    try {
                    if(in.ready()==true)
                    String tmp = in.readLine();
                    if (tmp != null) {
                        content.append(tmp);
                    }
    this way your thread isn't blocked if your bufferedReader isn't ready
    its probably because the data being sent is formatted in the wrong way or buffered reader has not buffered enough data

    hope this helps
    Last edited by mozly; 12-23-2011 at 04:17 AM.

  11. #11
    Potato is offline Member
    Join Date
    Dec 2011
    Posts
    25
    Rep Power
    0

    Default Re: Am I doing it horribly wrong?

    If you want to start a new thread, you don't call Thread.run(), you instead call Thread.start(). It's a common mistake :)

Similar Threads

  1. Replies: 4
    Last Post: 06-11-2013, 01:37 AM
  2. Replies: 10
    Last Post: 07-16-2010, 12:34 AM
  3. What am I doing wrong??
    By NoNickName in forum New To Java
    Replies: 3
    Last Post: 04-23-2009, 11:04 PM
  4. What did i do wrong
    By jpnym15 in forum New To Java
    Replies: 8
    Last Post: 11-17-2008, 10:07 AM
  5. what's wrong in here!!!
    By Annatar in forum New To Java
    Replies: 8
    Last Post: 11-14-2008, 02:55 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •