Search code examples
javasocketstelnet

How to setup server-client communication using Telnet via a NetManager class


We're working on a school project where we have to use Telnet (Yes, I know, we shouldn't use it etc., but we have to) to communicate between a server and a client. We have two classes setup, a server and a client, which is a thread. We called our client 'NetManager', it can send and receive messages.

However, we have other classes as well which need to send messages to the server, and handle the output the server returns. We want to do this via the NetManager, instead of setting up a new Thread and socket for each class individually.

However, we do not know how to do this. Ideally we want to have a while(working) { } in our NetManager class which reads the lines the server sends, but we also need to send messages inside the while loop. The messages needs to vary so simply putting them in the while loop won't work. Is there a way to do server-client communication, where multiple classes use the NetManager class to send and receive messages from a server?

I have included a stripped down version of our NetManager class below for reference. This version only reads lines sent by the server, it does not yet send messages (which could be accomplished with out.println(); .

public class NetManager extends Thread {
    private BufferedReader in;
    private BufferedReader stdIn;
    private PrintWriter out;
    private String line;

    @Override
    public void run() {
    boolean working = true;

        try {
            Socket sock = new Socket("localhost", 7789);
            out = new PrintWriter(sock.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (working) {
            try {
                line = in.readLine();
                System.out.println(line);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Here is a quick scheme I made of the best case scenario:

enter image description here


Solution

  • While I think your design is a good one I also think it may be overly complicated for what you are trying to do. If multiple classes are going to be using the same NetManager instance then you are going to have to implement some sort of locking and/or queuing so only one class tries to access NetManager at a time. Then you will also have to figure out some way to make sure any response received by NetManager gets back to the appropriate caller.

    Having said all that, I would have any classes that use NetManager accept an instance of it in the constructor. It would then save a reference to the object and use it as necessary.