SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Server and client program

    Hi all, Im having problems developing a client- server program. Basically I want the server to have a GUI (which Im still designing) that presents all clients on a network which allow the user to select to view info about a paticular client. Also faulty clients show a different color . The main function of the program is to communicate with the client program in regular intervals and check for good condition. Where communication cant be established or client take long to answer then a predefined msg is sent back. Thus far we ( a group of two) have not had much success as we hav been able to only send a string from the server to client as the code below shows:

    SERVER / MAIN UTILTY

    import java.net.*;
    import java.io.*;

    public class SimpleServer {
    public static void main(String args[]) {
    //server sic
    ServerSocket s = null;
    Socket s1;
    String sendString = "Connected Successfully!";
    OutputStream os;
    DataOutputStream dos;


    try {
    s = new ServerSocket(5432);
    } catch (IOException e)
    {
    }
    while (true)
    {
    try {

    // wait here and listen for a connection

    s1 = s.accept();




    //Get a communication stream associated with the socket

    os = s1.getOutputStream();

    dos = new DataOutputStream (os);


    //Send your string! (UTF provides machine independence)

    dos.writeUTF(sendString);




    // close the connection, but not the server socket

    dos.close();

    os.close();

    s1.close();
    } catch (IOException e) {
    // ignore
    } } }
    }

    //---still cant get this bit to retrive IP and hostname of client
    //to get host info
    /*try
    {
    InetAddress localaddr = InetAddress.getLocalHost();

    System.out.println ("Local IP Address : " + localaddr );
    System.out.println ("Local hostname : " + localaddr.getHostName());
    }
    catch (UnknownHostException e)
    {
    System.err.println ("Can't detect localhost : " + e);
    }*/


    CLIENT PROGRAM

    import java.net.*;
    import java.io.*;

    public class SimpleClient {
    public static void main(String args[]) throws IOException {

    Socket s1;
    InputStream s1In;
    DataInputStream dis;

    //opening a connection to host(IP) a
    s1 = new Socket("192.168.2.4", 5432);
    s1In = s1.getInputStream();
    dis = new DataInputStream(s1In);
    String st = new String(dis.readUTF( ));
    System.out.println(st);

    dis.close();

    s1In.close();
    s1.close();
    }
    }

    Questions: How can we be able get the client to send back a message if connection takes ages or client is faulty( just like pinging the client)?
    How can we retrieve the IP and say hostname of the client using the code above? any responses with comments for proper understanding will be immensely appreciated.

    EDIT:the program is to be run on a Linux/ Unix machine
    fresher

  2. #2
    SitePoint Evangelist borna's Avatar
    Join Date
    Jun 2006
    Location
    Iran, Tehran
    Posts
    475
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As far as IP concerns request.getRemoteAddr() gives the ip of cient.
    -1/2=999?

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by borna
    As far as IP concerns request.getRemoteAddr() gives the ip of cient.
    thanks..that works in returning the client IP...still stuck on the rest...someone pls help..thanks in advance.

  4. #4
    SitePoint Evangelist borna's Avatar
    Join Date
    Jun 2006
    Location
    Iran, Tehran
    Posts
    475
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Normally You must use a timer [to messure the time passed] and copmare with it each few seconds. If No response was send from client you may pointed out the connection is reset or the client has broken the communication.

    Is that waht you mean?
    -1/2=999?

  5. #5
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by borna
    Normally You must use a timer [to messure the time passed] and copmare with it each few seconds. If No response was send from client you may pointed out the connection is reset or the client has broken the communication.

    Is that waht you mean?
    If thats one way to implement it (i.e. the client returning a predefined msg about unsuccessful connection /timeout).. then thats what i mean but i cant just get my head around it..thanks in advance

  6. #6
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    what exactly does your client/server do? The way you have it, the server will send a message, the client reads it, then both will terminate.

    If you want to keep the connection established, there needs to be activity, or instruction to wait for activity (i.e. a loop of some sort).

    As far as checking that connections are still there, that would imply that you have more than one connection (i.e. a concurrent server). The way you have it now, there's only one client and one server.

  7. #7
    SitePoint Zealot
    Join Date
    Nov 2005
    Location
    Sweden
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Let the clients spawn their own threads. You could for example have a Client class on the server-side that extends class Thread or implements the Runnable interface. Furthermore it might be a good choice to have a ClientHandler class as well; also threaded and with a collection to put all connected clients in.
    Well, kind of hard to explain, take a look at this Java Chat Server...

  8. #8
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yeah, I normally do something like that, I've done several small client/server apps. I usually have a server, which has loop that accepts connections, once it receives a connection it passes the socket off to a ConnectionHandler which will be in a new thread, then the client is really dealing with the connection handler and the server waits for another connection.

  9. #9
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by rozner View Post
    yeah, I normally do something like that, I've done several small client/server apps. I usually have a server, which has loop that accepts connections, once it receives a connection it passes the socket off to a ConnectionHandler which will be in a new thread, then the client is really dealing with the connection handler and the server waits for another connection.
    thanks i think thats the sort of thing im talking about. any chance u could post some code pls? thanks in advance.

  10. #10
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well, I suppose I could post a very simple example:

    Simple server:
    Code:
    public class Server implements Runnable {
        public Server() throws IOException {
            serverSocket = new ServerSocket(9999);
        }
        
        public void run() {
            System.out.println("Ready for connections");
            for(;;) {
                try {
                    
                    Socket socket = this.serverSocket.accept();
                    
                    System.out.println("Connected to: " + socket.getRemoteSocketAddress());
                    
                    socket.setSoTimeout(30000);
                    
                    if (socket.isConnected()) {
                        new Thread(new ServerConnection(socket)).start();
                    }
                } catch (IOException e) {
                    System.err.println("An error has occured in the run method of the Server class: " + e.getMessage());
                }
            }
        }
    
        private ServerSocket serverSocket;
    }
    So in this case I'm not keeping track of the connections but I've done more complicated ones where I do, so instead of passing "new ServerConnection(...)" to the Thread constructor I would actually store that in a list first and then make a thread out of it. That way you can periodically iterate over that list and ping the clients to see if they're still there.

    Connection Handler
    Code:
    public class ServerConnection implements Runnable {
        public ServerConnection(Socket socket) {
            this.socket = socket;
        }
    
        public void run() {
    
            DataInputStream dis = null;
            DataOutputStream dos = null;
    
            try {
                dos = new DataOutputStream(socket.getOutputStream());
                dis = new DataInputStream(socket.getInputStream());
    
                String nextCommand = null;
    
                while (!(nextCommand = dis.readUTF()).equals("quit")) {
                    // do something based on nextCommand
                }
    
            } catch (Exception e) {
                // handle errors here
            }
        }
    }
    The "do something based on nextCommand" part is up to you, depending on what you're client/server is supposed to do. But that's the basic setup.

    Based on the code you've posted, I assume you can come up with the Client part yourself.

  11. #11
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by rozner View Post
    well, I suppose I could post a very simple example:

    Simple server:
    Code:
    public class Server implements Runnable {
        public Server() throws IOException {
            serverSocket = new ServerSocket(9999);
        }
        
        public void run() {
            System.out.println("Ready for connections");
            for(;;) {
                try {
                    
                    Socket socket = this.serverSocket.accept();
                    
                    System.out.println("Connected to: " + socket.getRemoteSocketAddress());
                    
                    socket.setSoTimeout(30000);
                    
                    if (socket.isConnected()) {
                        new Thread(new ServerConnection(socket)).start();
                    }
                } catch (IOException e) {
                    System.err.println("An error has occured in the run method of the Server class: " + e.getMessage());
                }
            }
        }
    
        private ServerSocket serverSocket;
    }
    So in this case I'm not keeping track of the connections but I've done more complicated ones where I do, so instead of passing "new ServerConnection(...)" to the Thread constructor I would actually store that in a list first and then make a thread out of it. That way you can periodically iterate over that list and ping the clients to see if they're still there.

    Connection Handler
    Code:
    public class ServerConnection implements Runnable {
        public ServerConnection(Socket socket) {
            this.socket = socket;
        }
    
        public void run() {
    
            DataInputStream dis = null;
            DataOutputStream dos = null;
    
            try {
                dos = new DataOutputStream(socket.getOutputStream());
                dis = new DataInputStream(socket.getInputStream());
    
                String nextCommand = null;
    
                while (!(nextCommand = dis.readUTF()).equals("quit")) {
                    // do something based on nextCommand
                }
    
            } catch (Exception e) {
                // handle errors here
            }
        }
    }
    The "do something based on nextCommand" part is up to you, depending on what you're client/server is supposed to do. But that's the basic setup.

    Based on the code you've posted, I assume you can come up with the Client part yourself.


    Hi many thanks for your time. Im kinda of struggling to come up with the client. Not quite sure what to take out of the client code that was posted initially. thanks


Bookmarks

Posting Permissions

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