Results 1 to 16 of 16
  1. #1
    pinheiroa is offline Member
    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0

    Default Problem with Sockets

    hello,

    I'm having problems with this server socket class (multi threading) and I don't know how to solve it.
    I'm able to connect from a client and send a messege to this server and it does what I want wich is put it into a list and then write it on a Jpanel. The problem is when I send a second message from client to server, is simply doesn't work.
    Can anybody help me, pls?


    Here's the code:

    Java Code:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    
    
    public class Server extends Thread{
    
        boolean active = true;
        int portServidor = 54321;
        BufferedReader in;
        placard placa;
        boolean Istrue = true;
        String input;
        PrintWriter outt = null;
        ServerWorker sworker = new ServerWorker();
    
    
        public Server(placard pub) {
            super("ServerThread");
            placa = new placard();
            //placa = pub;
            placa.setVisible(true);
    
        }
    
        public void run(){
           while (true) {
                try {
                    ServerSocket server = new ServerSocket(portServidor);
                    System.out.println("Listening...");
                    
                    
                    while(active){
                        Socket socket = server.accept();
                        String ip = String.valueOf(socket.getInetAddress());
                        //writes into the Jpanel the cleint's IP
                        placa.novaLigacao("");
                        placa.novaLigacao(ip);
    
                         in = new BufferedReader(
                                            new InputStreamReader(
                                            socket.getInputStream()));
                         outt = new PrintWriter(socket.getOutputStream(), true);
                         input = in.readLine();
    
                         
                         //do a check to the prefix of message to choose what to do next - put in the list or remove from the list
                         sworker.doOperacao(input);
                       
                         //writes next message from the list into the "wall"
                         placa.escreve(sworker.getMensagem());
                         //in.close();
                         //outt.close();
    
    
                     }
                     //socket.close();
                } catch (IOException e) {
                    System.out.println(e);
                   
                }
            
                System.out.println("Exit");
            }
    
       }
     
       
    
        public static void main(String[] args) throws IOException {
            new Server(null).start();
    
        }
     
    }
    Last edited by Fubarable; 09-05-2010 at 07:40 PM. Reason: Moderator Edit: Code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Not sure if this is your problem, but where do you create and run separate threads for each client recognized by the server?

  3. #3
    pinheiroa is offline Member
    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0

    Default

    I'm not sure if I understand your question, but a new thread is started when I run this class (it's not a real world program).

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by pinheiroa View Post
    I'm not sure if I understand your question, but a new thread is started when I run this class (it's not a real world program).
    No, that's not what I meant. If this is truly a sever that services multiple clients, real-world or not, it must create a new thread each time the server connects with a new client.

    Again, I'm no pro at this, far from it, so corrections are most welcome, but for instance,

    Java Code:
    class MyServer {
       public static final int PORT_NUMBER = 4442;
       private ServerSocket serverSocket;
       private boolean keepGoing = true;
    
       public MyServer() {
          try {
             // start the server listening
             serverSocket = new ServerSocket(PORT_NUMBER);
          } catch (IOException e) {
             System.err.println("Could not listen on port: " + PORT_NUMBER + ".");
             System.exit(1);
          }
          while (keepGoing) {
             Socket clientSocket = null;
             try {
                // if connects to a client
                clientSocket = serverSocket.accept();
    
                // create a runnable that services the client
                MyServerRunnable myServRunnable = new MyServerRunnable(clientSocket);
    
                // and run this in its own thread
                new Thread(myServRunnable).start();
             } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
             }
          }
          if (serverSocket != null) {
             try {
                serverSocket.close();
             } catch (IOException e) {
                e.printStackTrace();
             }
          }
    
       }
    
    }
    
    // a Runnable to allow the server to service the client
    class MyServerRunnable implements Runnable {
       private Socket clientSocket;
       private PrintWriter out;
       private BufferedReader in;
       private String inputLine, outputLine;
    
       public MyServerRunnable(Socket clientSocket) {
          this.clientSocket = clientSocket;
       }
    
       public void run() {
          try {
             out = new PrintWriter(clientSocket.getOutputStream(), true);
             in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             long time = System.currentTimeMillis();
             while ((inputLine = in.readLine()) != null) {
                // get input from client and send out any output...
             }
          } catch (IOException e) {
             e.printStackTrace();
          }
          try {
             if (out != null) {
                out.close();
             }
             if (in != null) {
                in.close();
             }
             if (clientSocket != null) {
                clientSocket.close();
             }
          } catch (IOException e) {
             e.printStackTrace();
          }
       }
    }

    For more on this, please check out the Oracle IO tutorial, and in particular, the section on "Supporting Multiple Clients"

    Luck!

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Sorry, (if this is a single client app) I'm wrong. One of your problems I believe is that your server has no while loop with which to service the client; this portion in my example above:

    Java Code:
             while ((inputLine = in.readLine()) != null) {
                // get input from client and send out any output...
             }
    Again, the tutorial will explain this to you: Client-Server Tutorial

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,873
    Rep Power
    25

    Default

    when I send a second message from client to server, is simply doesn't work.
    Where does the server code stop executing? Is it blocked waiting for a connection or ???
    Does it throw an exception?

  7. #7
    pinheiroa is offline Member
    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0

    Default

    This is ment to serve multiple clients.
    There's no Exception.

    I think the problems is in this part:

    while(active){
    Socket socket = server.accept();

    With this, it accepts multiple clients but each client only can send one message (the second "server.accept()" doesnt work because there's already a connection).

    If I put the server.accept() before the while(active) loop, the client can send as many messages we wants, but of course this prevents other clients to connect.

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,873
    Rep Power
    25

    Default

    I think the problems is in this part:
    Why do you think that statement is the problem?
    have you put print outs before and after that statement to show that is where the server is stopping?

    Look at the code Fubarable posted.
    Here is the server loop in a server I use for testing:
    Java Code:
                while (true) {    // Forever loop
                  Socket s = ss.accept();  // Wait for client
                  
                  if (stopped) {                 // were we asked to stop? 
                    log.log("run(S): stopping");
                    return;         // Early exit if stopped   
                  }  
                  log.log("run(S): " + ++runS_connects + " connection accepted: " + s
                                                  + " TO:" + s.getSoTimeout());
                  hisIP = s.getInetAddress().getHostAddress();    // extract IP addr 
          
                  HandleRequest dr = new HandleRequest(s, httpd.this); // process request
                }  // end while() Forever loop

  9. #9
    pinheiroa is offline Member
    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Why do you think that statement is the problem?
    have you put print outs before and after that statement to show that is where the server is stopping?

    [/code]
    I've tested this server.accept() before and after the loop and the outcome was just like I said. I also used the debug mode in netbeans (step into trace) and it get stucked on that part two.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Let's look at your code. Here the server will connect with a single client:
    Java Code:
                    while(active){
                        // the server here connects with a client
                        Socket socket = server.accept();


    And here, your server connects with the client's streams
    Java Code:
                         in = new BufferedReader(
                                            new InputStreamReader(
                                            socket.getInputStream()));
                         outt = new PrintWriter(socket.getOutputStream(), true);

    And here you read in a single line from the client's input stream:
    Java Code:
                         input = in.readLine();
    But where do you read in the rest of the lines? You need a while ((input = in.readLine()) != null) block here to catch all the lines coming in.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Norm View Post
    Why do you think that statement is the problem?
    have you put print outs before and after that statement to show that is where the server is stopping?

    Look at the code Fubarable posted.
    Here is the server loop in a server I use for testing:
    Java Code:
                while (true) {    // Forever loop
                  Socket s = ss.accept();  // Wait for client
                  
                  if (stopped) {                 // were we asked to stop? 
                    log.log("run(S): stopping");
                    return;         // Early exit if stopped   
                  }  
                  log.log("run(S): " + ++runS_connects + " connection accepted: " + s
                                                  + " TO:" + s.getSoTimeout());
                  hisIP = s.getInetAddress().getHostAddress();    // extract IP addr 
          
                  HandleRequest dr = new HandleRequest(s, httpd.this); // process request
                }  // end while() Forever loop
    Norm:
    I'm guessing that your HandleRequest constructor creates and runs a thread that allows the client and server to communicate and within that thread has a while (true) loop where the client's streams are dealt with, correct?

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,873
    Rep Power
    25

    Default

    Fubarable:
    Yes, that's correct.

    pinheiroa
    Assuming that the server code is correct. My and Fubarable's experiences are that it is.
    Then are you sure that there is a client trying to connect to the server?

  13. #13
    pinheiroa is offline Member
    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0

    Default

    yap, quite sure.
    I tested my client againts your server code example and it works just fine.
    I can send more than one message and also use multiple clients. Am I allowed to use part of your code?
    I think it solves my problem!

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

  15. #15
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,873
    Rep Power
    25

    Default

    My code is worth what you pay for it. It's absolutely free.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Replies: 6
    Last Post: 11-19-2009, 12:39 AM
  2. TCP sockets problem
    By duffman.sk in forum Networking
    Replies: 1
    Last Post: 10-30-2009, 06:06 AM
  3. Problem (sockets)
    By Blacknight962 in forum New To Java
    Replies: 3
    Last Post: 08-16-2009, 01:56 AM
  4. Sockets and JFrames problem
    By marcg11 in forum Advanced Java
    Replies: 6
    Last Post: 08-15-2009, 02:07 PM
  5. Sockets NIO
    By aamp in forum New To Java
    Replies: 3
    Last Post: 01-15-2009, 11:56 AM

Tags for this Thread

Posting Permissions

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