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.

Page 1 of 3 123 LastLast
Results 1 to 25 of 52

Thread: can someone help me in this server and multi client

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default can someone help me in this server and multi client

    (server)



    import java.awt.BorderLayout;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Date;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;


    public class MultithreadServer extends JFrame{
    private JTextArea jtaDisplay = new JTextArea();
    InetAddress inetAddress;
    String[] allmessage = new String[1000000];
    int chatlog;
    DataOutputStream outputToClient;
    DataInputStream inputFromClient;


    public MultithreadServer(){
    jtaDisplay.setEditable(false);
    add(new JScrollPane(jtaDisplay), BorderLayout.CENTER);
    setTitle("Multi-Thread Server");
    setSize(500,300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    try{

    ServerSocket serverSocket = new ServerSocket(8000);
    jtaDisplay.append("Multi-Thread Server start at " + new Date() + "\n");

    int clientNo = 1;
    chatlog = 0;

    while(true){
    Socket socket = serverSocket.accept();
    // Find the client's host name, and IP address
    inetAddress = socket.getInetAddress();
    outputToClient = new DataOutputStream(socket.getOutputStream());
    inputFromClient = new DataInputStream(socket.getInputStream());

    outputToClient.writeInt(chatlog);


    HandleAClient task = new HandleAClient(socket);
    new Thread(task).start();
    clientNo++;
    }
    }catch(IOException ex){
    System.err.println(ex);
    }
    }

    public static void main(String[] args){
    new MultithreadServer();
    }

    class HandleAClient implements Runnable{
    private Socket socket;

    public HandleAClient(Socket socket){
    this.socket = socket;
    }

    public void run(){
    try{
    while(true){
    String msgtoreturn = "";

    int log = inputFromClient.readInt();

    jtaDisplay.append( allmessage[chatlog] + "\n");
    chatlog++;
    outputToClient.writeInt(chatlog);

    for(int i = log;i<chatlog;i++){
    msgtoreturn = msgtoreturn + allmessage[i] + "\n";
    }

    outputToClient.writeUTF(msgtoreturn);
    }
    }catch(IOException ex){
    System.err.println(ex);
    }
    }

    }

    }


    (client)




    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;


    public class Client extends JFrame{
    private JTextField jtfMessage = new JTextField();
    private JTextArea jtaDisplay = new JTextArea();

    private DataOutputStream toServer;
    private DataInputStream fromServer;
    int log;
    Socket socket ;


    public Client(){
    jtaDisplay.setEditable(false);
    JPanel jp = new JPanel(new BorderLayout());
    jp.add(new JLabel("Enter Message: "), BorderLayout.WEST);
    jp.add(jtfMessage, BorderLayout.CENTER);
    jtfMessage.setHorizontalAlignment(JTextField.RIGHT );

    add(jp,BorderLayout.NORTH);
    add(new JScrollPane(jtaDisplay),BorderLayout.CENTER);

    setTitle("Client");
    setSize(500, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    try{
    socket = new Socket("localhost", 8000);

    fromServer = new DataInputStream(socket.getInputStream());
    toServer = new DataOutputStream(socket.getOutputStream());
    log = fromServer.readInt();

    }catch(IOException ex){
    jtaDisplay.append(ex.toString() + "\n");
    }

    jtfMessage.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    try{



    toServer.writeInt(log);
    toServer.writeUTF(jtfMessage.getText().trim());
    toServer.flush();

    log = fromServer.readInt();
    String allmessage = fromServer.readUTF();
    jtaDisplay.append(allmessage);

    jtfMessage.setText("");


    }catch(IOException ex){
    System.err.println(ex);
    }
    }
    });
    }



    public static void main (String[] args){
    new Client();
    }

    }





    the problem start when i open second client .


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: can someone help me in this server and multi client

    Quote Originally Posted by wuliao123 View Post
    the problem start when i open second client .
    This doesn't tell us much. If you don't get help soon, consider putting in some more effort to tell the details about your problem. Also check the forum's FAQ to see how to post code using code tags so we will be able to see your code's formatting, allowing us to read it and understand it.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    sorry for make you all hard to understand . It my first experience to use forum.
    the problem is when i open second client and use it still ok...but then i change back to first client (i hope the first client able to receive msg from what second client have input) but when i change back to first client the method "fromServer = new DataInputStream" inside the client's button listener seem like cannot work

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    Try debugging the code by adding lots of println statements that print out messages to show execution flow and the values of variables as the code executed. Seeing what the computer sees when it executes the code will help you understand what it is doing and where it is going wrong.

    Please edit your post and wrap your code with
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    jtfMessage.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    try{
     
     
     
    toServer.writeInt(log);
    toServer.writeUTF(jtfMessage.getText().trim());
    toServer.flush(); 
     
    log = fromServer.readInt();
    String allmessage = fromServer.readUTF();
    jtaDisplay.append(allmessage);
     
    jtfMessage.setText("");
     
     
    }catch(IOException ex){
    System.err.println(ex);
    }
    }
    });
    }

    i try already, it stop at log = fromServer.readInt(); i just do not get it why it work normally until i open second client then use back the first client

    the log = fromServer.readInt(); seem like unable to receive the data

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    it stop at log = fromServer.readInt();
    Is there anything to read there?

    why it work normally until i open second client then use back the first client
    Can you post the debug output from the program that shows what it does and explain what the problem is and say what the code should do?

    The posted code is not formatted properly. There are no indentations for nested statements.


    One problem I see is the code does a read inside a listener. If the data isn't ready, that will hang the GUI while it waits.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    testing.jpg

    I was hope that the server will store the input from the client( it store in an String array in the server), when another(second) client it open and have input into the server the server will also store the input , when the 1st client input again, the server will sent the message that have been input to server by the second client to the first client so that the first client able to see the message from second client, but when i try make the first client to have input again it jz stop . ( it similar with when i just put log = fromServer.readInt(); but without integer output from the server)

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    To debug this code you need to add lots of println statements that shows what the code is doing.

    I use this driver so that all the output is in one console and the order of events can easily be seen
       public static void main(final String[] args) {    //<<<<<<<<<<<<<<<<<<<
     
          Thread t1 = new Thread(new Runnable() {
             public void run() {
                MultithreadServer.main(args);
             }
          });
          t1.start();
     
          try{Thread.sleep(100);}catch(Exception x){}
     
          Thread t2 = new Thread(new Runnable() {
             public void run() {
                Client.main(args);
             }
          });
          t2.start();
          Thread t3 = new Thread(new Runnable() {
             public void run() {
                Client.main(args);
             }
          });
          t3.start();
     
     
          // wait and exit
          try{Thread.sleep(30000);}catch(Exception x){}
          System.out.println(">>>>>>>>Exiting main");
          System.exit(0);
       }  //  end main
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    Sorry for not able to provide more detail for you all to help me

    i use that driver , it help open so many server. only one server can be use, the rest (java.net.BindException: Address already in use: JVM_Bind)

    then another one is
    Exception in thread "Thread-1145" java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:691)
    at Client.main(Client.java:106)
    at Client$4.run(Client.java:109)
    at java.lang.Thread.run(Thread.java:722)

    --- Update ---

    Quote Originally Posted by Norm View Post
    One problem I see is the code does a read inside a listener. If the data isn't ready, that will hang the GUI while it waits.
    i think this is my problem because my gui really hang, but it not happen anything if i no open second client.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    How are you using the driver I posted? It starts one server and two clients.

    The code needs lots of printlns to show you what it is doing.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    i replace the main inside client with the driver.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    The code I posted should not be in either the server or the client classes. It should be in its own class.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    this time,i straight cannot input . it seem like the read cannot be use when got more than one client . what other method can be use ,because i want message to be update when i press enter

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    Move code out of the listener so that the read does not hang the GUI. Put the code that does a read on its own thread so the listener code can return immediately and release the GUI's thread.


    You need to debug the code to see what it is doing. Add println messages before and after all reads and before and after all writes that print out the data that being sent and received.
    Make sure that every time data is written that it is being read. There should be a completed read for every write.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    Quote Originally Posted by Norm View Post
    Put the code that does a read on its own thread so the listener code can return immediately and release the GUI's thread.
    mind to show me some example?

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    show me some example?
    Here is a sample of how to use println statements for debugging:
                        System.out.println(name +" C - reading1");
                        log = fromServer.readInt();    
                        System.out.println(name +" C - read log="+log);

    Here is an example of using a thread to execute some code:
          Thread t2 = new Thread(new Runnable() {
             public void run() {
                 //  put code to execute here or call a method
             }
          });
          t2.start();

    Please edit your post and wrap your code with
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    i use println to debug . at server i use writeInt and writeUTF ,client there use readInt and readUTF

    but the value i readInt is different from writeInt when my server there have another writeUTF

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    can you post the debug output that shows what you are talking about?
    The writes and reads must match. When one side writes a value the other side must read that value.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    erm....i already make changes to my code . that matching problem already solve but it come back to last time problem, the first client read there cannot work after the second client run. The read i put inside the listener really wrong ?

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    Can you post the current version of the code for testing?
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    server
     
    import java.awt.BorderLayout;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Date;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
     
    public class MultithreadServer extends JFrame{
        private JTextArea jtaDisplay = new JTextArea();
        InetAddress inetAddress;
        String[] allmessage = new String[1000000];
       int chatlog=0;
     
        DataOutputStream outputToClient;
        DataInputStream inputFromClient;
     
     
        public MultithreadServer(){
             jtaDisplay.setEditable(false);
            add(new JScrollPane(jtaDisplay), BorderLayout.CENTER);
            setTitle("Multi-Thread Server");
            setSize(500,300);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
     
            try{
     
                ServerSocket serverSocket = new ServerSocket(8000);
                jtaDisplay.append("Multi-Thread Server start at " + new Date() + "\n");
     
                int clientNo = 1;
     
     
                while(true){
                    Socket socket = serverSocket.accept();
            inetAddress = socket.getInetAddress();
              outputToClient = new DataOutputStream(socket.getOutputStream());
             inputFromClient = new DataInputStream(socket.getInputStream());  
     
                   outputToClient.writeInt(chatlog);
     
                    HandleAClient task = new HandleAClient(socket);
                    new Thread(task).start();
                    clientNo++;
                }
            }catch(IOException ex){
               System.err.println(ex);
            }
        }
     
        public static void main(String[] args){
            new MultithreadServer();
        }
     
        class HandleAClient implements Runnable{
            private Socket socket;
     
            public HandleAClient(Socket socket){
                this.socket = socket;
            }
     
            public void run(){
                try{
                while(true){               
                  String  msgtoreturn = "";
     
                     int  log = inputFromClient.readInt();         
     
                            allmessage[chatlog] = inetAddress.getHostName() + "\t" +inputFromClient.readUTF();
                        jtaDisplay.append( allmessage[chatlog] + "\n");
                        chatlog = chatlog+1;             
                       outputToClient.writeInt(chatlog);
     
                      for(int i = log;i<chatlog;i++){
                           msgtoreturn = msgtoreturn + allmessage[i] + "\n";
                      }
                        System.out.print(msgtoreturn);
                       outputToClient.writeUTF(msgtoreturn);
                       outputToClient.flush();
                    }
                }catch(IOException ex){
                    System.err.println(ex);
                }
            }
     
        }
     
    }

    Client
     
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
     
     
    public class Client extends JFrame{
        private JTextField jtfMessage = new JTextField();
        private JTextArea jtaDisplay = new JTextArea();
     
        private DataOutputStream toServer;
        private DataInputStream fromServer;
        int log;
          Socket socket ;
          String allmessage ;
     
     
        public Client(){
             jtaDisplay.setEditable(false);
            JPanel jp = new JPanel(new BorderLayout());
            jp.add(new JLabel("Enter Message: "), BorderLayout.WEST);
            jp.add(jtfMessage, BorderLayout.CENTER);
            jtfMessage.setHorizontalAlignment(JTextField.RIGHT);
     
            add(jp,BorderLayout.NORTH);
            add(new JScrollPane(jtaDisplay),BorderLayout.CENTER);
     
            setTitle("Client");
            setSize(500, 300);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
     
            try{
                 socket = new Socket("localhost", 8000);
     
                fromServer = new DataInputStream(socket.getInputStream());
                toServer = new DataOutputStream(socket.getOutputStream());
                log = fromServer.readInt();
     
     
            }catch(IOException ex){
                        jtaDisplay.append(ex.toString() + "\n");
            }
     
            jtfMessage.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    try{
                        toServer.writeInt(log);
                        toServer.writeUTF(jtfMessage.getText().trim());
                        toServer.flush();        
     
                        readchatlog();
                        readchatmessage();
                            jtfMessage.setText("");
                 }catch(IOException ex){
                        System.err.println(ex);
                    }
                }
            });
        }
     
     
     
        public static void main (String[] args){
            new Client();
        }
         public void readchatlog(){
             try {    
                 System.out.println("read log");
                             log = fromServer.readInt();
                               System.out.println("log "  +  "\t" + log);
                         } catch (IOException ex) {
                             Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                         }
        }
        public void readchatmessage(){
             try {    
                  System.out.println("read msg");
                             allmessage = fromServer.readUTF();
                              jtaDisplay.append(allmessage);
                               System.out.println("log "  +  "\t" + allmessage);
     
                         } catch (IOException ex) {
                             Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                         }
        }
    }

    it only function normal when got one client

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    The code still is trying to do too much in the listener. The listener needs to do some job and return as quickly as possible. If the code in the listener takes too long it will hang the GUI.
    Move any long running code to its own thread and let the listener exit quickly.
    If you don't understand my answer, don't ignore it, ask a question.

  23. #23
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

      jtfMessage.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    try{
                        toServer.writeInt(log);
                        toServer.writeUTF(jtfMessage.getText().trim());
                        toServer.flush();        
     
                        Thread t2 = new Thread(new Runnable() {
             public void run() {              
                readchatlog();
                readchatmessage();
                             }
          });
          t2.start();
     
                            jtfMessage.setText("");
                 }catch(IOException ex){
                        System.err.println(ex);
                    }
                }
            });

    after i try this the gui no more hang, but still the same...after second client run the first client read become unable to use. the code still too much in listener?

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can someone help me in this server and multi client

    the first client read become unable to use
    Where does the code in the first client have the problem? Is it waiting to read something or what do you mean by "unable to use"?
    What is the last statement that the code executes in the client before it "become unable to use"?
    If you don't understand my answer, don't ignore it, ask a question.

  25. #25
    Junior Member
    Join Date
    Feb 2013
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: can someone help me in this server and multi client

    all client have the same code... when i open one client(first client) the action listener does not have any problem. then i open second client and do the same..the action listener also does have any problem but then i try to make the first client to receive what have been input from the second client so i run the first client action listener again. but that time it only can run till read there then it seem like read something like what you say (toServer still can work only till the readchatlog(); as the readInt is inside the method)

Page 1 of 3 123 LastLast

Similar Threads

  1. my encrypting simple client to server program unable to get the key from client
    By Paytheprice in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 3rd, 2013, 07:15 AM
  2. Replies: 0
    Last Post: May 31st, 2012, 05:35 PM
  3. server/client application fails when client closes
    By billykid in forum Java Networking
    Replies: 4
    Last Post: January 26th, 2012, 01:54 AM
  4. Threads in multi client-server application
    By KingOfClubs in forum Threads
    Replies: 1
    Last Post: June 11th, 2011, 12:10 AM
  5. Replies: 1
    Last Post: March 23rd, 2010, 02:29 AM