Results 1 to 9 of 9
  1. #1
    Koren3 is offline Member
    Join Date
    Apr 2009
    Posts
    50
    Rep Power
    0

    Default [SOLVED] TCP chat Handler

    Hallo,
    I do multiclient chat and I need some inpiration for creating object handler. Now i have just this code:
    Server part.
    Java Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     *
     * @author Lolek
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            try {
                
    
                ServerSocket socket = new ServerSocket(5000);
                while (true) {
                    Socket accept = socket.accept();
                    new SocketThread(accept).start();
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
          
          
        }
    
    }
    
    class SocketThread extends Thread
    {
        Socket socket;
        
        public SocketThread(Socket socket)
        {
            this.socket=socket;
        }
        public void run()
        {
            BufferedReader read = null;
            try {
                read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter write = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    
                String line;
                while (true) {
                    write.write(read.readLine());
                    write.newLine();
                    write.flush();
                    System.out.println(read.readLine());
                }
            } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    read.close();
                } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    Client part:
    Java Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     *
     * @author Lolek
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            try {
                String addressIP;
                if (args.length == 0) {
                    addressIP = "127.0.0.1";
                } else {
                    addressIP = args[0];
                }
                Socket socket = new Socket(addressIP, 5000);
    
                BufferedReader read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedReader readKeyboard = new BufferedReader(new InputStreamReader(System.in));
                BufferedWriter write = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    
                while (true) {
                    String line = readKeyboard.readLine();
                    write.write(line);
                    write.newLine();
                    write.flush();
                    System.out.println(read.readLine());
                }
            } catch (UnknownHostException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    
    }

  2. #2
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    Handling what objects?
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  3. #3
    Koren3 is offline Member
    Join Date
    Apr 2009
    Posts
    50
    Rep Power
    0

    Default

    I wrote wrong. How can I do that, Server have some database name, IP address users. And one user e.g. John want communicate with Alicia. How can I do this connection?

  4. #4
    Koren3 is offline Member
    Join Date
    Apr 2009
    Posts
    50
    Rep Power
    0

    Default

    This i found on internet but donīt work.
    Java Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Vector;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     *
     * @author Lolek
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            try {
                int port = 5000;
                ServerSocket serverSocket = null;
                Socket socket = null;
    
                serverSocket = new ServerSocket(port);
                while (true) {
                    socket = serverSocket.accept();
                    ChatHandler handler = new ChatHandler(socket);
                    handler.start();
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            
          
          
        }
    }
    class ChatHandler extends Thread
    {
         static Vector handlers = new Vector(10);
         private Socket socket;
         private BufferedReader read;
         private BufferedWriter write;
         
         public ChatHandler(Socket socket)
         {
            try {
                this.socket = socket;
                this.read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                this.write = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            } catch (IOException ex) {
                Logger.getLogger(ChatHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
         
         public void run(){
         String line;
    	synchronized(handlers) {
    	    handlers.addElement(this);
     // add() not found in Vector class
    	}
    	try {
    	    while(!(line = read.readLine()).equalsIgnoreCase("/q")) {
    		for(int i = 0; i < handlers.size(); i++) {	
    			synchronized(handlers) {
    		            ChatHandler handler =
    			        (ChatHandler)handlers.elementAt(i);
    		        System.out.println(line + "\r");
    			System.out.flush();
    			}
    		}
    	    }
    	} catch(IOException ioe) {
    	    ioe.printStackTrace();
    	} finally {
    	    try {
    		read.close();
    		write.close();
    		socket.close();
    	    } catch(IOException ioe) {
    	    } finally {
    		synchronized(handlers) {
    		    handlers.removeElement(this);
    		}
    	    }
    	}
        }
    }

  5. #5
    Koren3 is offline Member
    Join Date
    Apr 2009
    Posts
    50
    Rep Power
    0

    Default

    Maybe server i solved but know i donīt know where is error. I think in client.
    Client code:
    Java Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    /**
     *
     * @author Lolek
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
             try {
                String addressIP;
                if (args.length == 0) {
                    addressIP = "127.0.0.1";
                } else {
                    addressIP = args[0];
                }
                Socket socket = new Socket(addressIP, 5000);
    
                BufferedReader read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedReader readKeyboard = new BufferedReader(new InputStreamReader(System.in));
                PrintWriter write = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    
                while (true) {
                    String line = readKeyboard.readLine();
                    write.write(line+ "\r");
                    write.flush();
                    System.out.println(read.readLine());
                }
            } catch (UnknownHostException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
    }

  6. #6
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    We don't know what you're trying to do. "Don't work" is not a very descriptive term.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  7. #7
    Koren3 is offline Member
    Join Date
    Apr 2009
    Posts
    50
    Rep Power
    0

    Default

    Yes i am sory. OK I remaked a little. Now Clients connect to server. Client send first message and another client recive this message but only first message. Second message is lost. Another client recive until first client send 4. message and this client must something write. I think Output block Input somewhere but i donīt know where.
    Servec code:
    Java Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Vector;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     *
     * @author Lolek
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            try {
                int port = 5000;
                ServerSocket serverSocket = null;
                Socket socket = null;
    
                serverSocket = new ServerSocket(port);
                while (true) {
                    socket = serverSocket.accept();
                    ChatHandler handler = new ChatHandler(socket);
                    handler.start();
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            
          
          
        }
    }
    class ChatHandler extends Thread
    {
         static Vector handlers = new Vector(10);
         private Socket socket;
         private BufferedReader read;
         private BufferedWriter write;
         
         public ChatHandler(Socket socket)
         {
            try {
                this.socket = socket;
                this.read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                this.write = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            } catch (IOException ex) {
                Logger.getLogger(ChatHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
         
        
         public void run(){
         String line=null;
    	synchronized(handlers) {
    	    handlers.addElement(this);
     // add() not found in Vector class
    	}
    	try {
    	    while(!(line = read.readLine()).equalsIgnoreCase("/q")) {
    		for(int i = 0; i < handlers.size(); i++) {	
    			synchronized(handlers) {
    		            ChatHandler handler = (ChatHandler)handlers.elementAt(i);                        
                                handler.write.write(line);
                                handler.write.newLine();
                                handler.write.flush();
                                System.out.println(read.readLine()+"\r\n");
    			}
    		}
    	    }
                
    	} catch(IOException ioe) {
    	    ioe.printStackTrace();
    	} finally {
    	    try {
    		read.close();
    		write.close();
    		socket.close();
    	    } catch(IOException ioe) {
    	    } finally {
    		synchronized(handlers) {
    		    handlers.removeElement(this);
    		}
    	    }
    	}
        }
    }
    Client code:
    Java Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     *
     * @author Lolek
     */
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
           String addressIP;
           if (args.length == 0) {
                    addressIP = "127.0.0.1";
                } 
           else {
                    addressIP = args[0];
                }
           ReciveT recive = new ReciveT(addressIP,5000);
           SendT send = new SendT(recive.getSocket());
        }
    
    }
    
    class ReciveT implements Runnable
    {
        private Socket socket;
        private String IPAddress;
        private int port;
        
        ReciveT(String IPAddress,int port)
        {   
            try {
                this.IPAddress = IPAddress;
                this.port = port;
                this.socket = new Socket(IPAddress, port);
                new Thread(this, "Recive thread").start();
            } catch (UnknownHostException ex) {
                Logger.getLogger(ReciveT.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ReciveT.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        public Socket getSocket()
        {
            return this.socket;
        }
        public void run()
        {
            BufferedReader read = null;
            try {
                read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = null;
                while ((line = read.readLine()) != null) {
                    System.out.println(line);
                    System.out.flush();
                }
            } catch (IOException ex) {
                Logger.getLogger(ReciveT.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    read.close();
                } catch (IOException ex) {
                    Logger.getLogger(ReciveT.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    class SendT implements Runnable
    {
        private Socket socket;
        
        SendT(Socket socket)
        {
            this.socket = socket;
            new Thread(this, "Send Thread").start();
        }
        public void run()
        {
            BufferedWriter write = null;
            try {
                BufferedReader readKeyboard = new BufferedReader(new InputStreamReader(System.in));
                write = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    
                String line;
                while ((line = readKeyboard.readLine()) != null) {
                    write.write(line);
                    write.newLine();
                    write.flush();
                }
            } catch (IOException ex) {
                Logger.getLogger(SendT.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    write.close();
                } catch (IOException ex) {
                    Logger.getLogger(SendT.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

  8. #8
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    What's up with the Vector of handlers? The point of having separate threads is so each thread deals with its own connection. Synchronising on it also prevents other threads from running concurrently. Plus, if you really want a vector of handles, use Vector<ChatHandler>
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  9. #9
    Koren3 is offline Member
    Join Date
    Apr 2009
    Posts
    50
    Rep Power
    0

    Default

    I solved it. And in place of vector I used ArrayList . Thank you for your reply.

Similar Threads

  1. zip a file tp data handler
    By beginer@1234 in forum New To Java
    Replies: 2
    Last Post: 04-27-2009, 06:04 AM
  2. CheckedTreeDialog adding Handler/Listener
    By negroscuro in forum SWT / JFace
    Replies: 5
    Last Post: 03-30-2009, 06:30 AM
  3. event handler not working properly
    By H3rtaherta in forum Java 2D
    Replies: 3
    Last Post: 11-24-2008, 02:39 AM
  4. JList and JButton event handler not working
    By H3rtaherta in forum AWT / Swing
    Replies: 3
    Last Post: 11-22-2008, 12:00 AM
  5. Help with Handler
    By baltimore in forum AWT / Swing
    Replies: 1
    Last Post: 08-04-2007, 09:42 PM

Posting Permissions

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