Search code examples
javasocketsclient-serverserversocket

(Client - Server) Java control when Server's serversocket accepts client(s) is not working


I am currently learning about Sockets and my homework is to create a chat room where multiple clients can talk freely. The hint given by the teacher was that the chat room server only accepts the client when the client attempts to send a message. This homework is supposed to be done without using threads.

Following the hint given, I tried to create unbound ServerSocket and Socket in both the client and the server code. The key idea is that when the client attemps to send a message to the server, the client code would connect the unbound Socket, which will then trigger the server to connect the unbound ServerSocket and to accept the client.

However, when I run the code, both the server and client code are running, and they claim that all the connections are made, but I could not transmit messages between the client and the server at all.

I have tried finding answers online, but I could not find any. I would like to ask if my way of deciding when the server accepts the client is correct.

my ChatRoom Server:

public class ChatRoom {
    public static void main(String[] args) throws Exception {

        int portNum = 4321;

        ServerSocket serverSocket = new ServerSocket();

        int count = 1;

        while (true) {

            // redeclare everything each round
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            BufferedReader stdIn = null;
            String inputLine = null;

            // accept each time round
            serverSocket.bind(new InetSocketAddress(portNum));
            socket = serverSocket.accept();
            System.out.println("newly accepted!");

            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            stdIn = new BufferedReader(new InputStreamReader(System.in));

            if (!((inputLine = in.readLine()).equals("Bye"))) {
                System.out.println("Client says: " + inputLine);
                out.println(stdIn.readLine());
                out.flush();

                System.out.println("Message Count: " + count);
                count++;
            }
            else {
                out.println(inputLine);
                serverSocket.close();
                socket.close();
                out.close();
                in.close();
            }
        }
    }   
}

my ChatRoomClient:

public class ChatRoomClient {
    public static void main(String[] args) throws Exception {
        String hostName = "localhost";
        int portNumber = 4321;

        Socket echoSocket = new Socket();   // creates an unbound socket

        PrintWriter out = null;
        BufferedReader in = null;
        BufferedReader stdIn = null;

        String userInput;
        do {
            out = null;
            in = null;
            stdIn = null;

            // each time round the unbound socket attempts to connect to send a message
            echoSocket.connect(new InetSocketAddress(hostName, portNumber));
            System.out.println("successfully connected");
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
            stdIn = new BufferedReader(new InputStreamReader(System.in));

            userInput = stdIn.readLine();
            out.flush();
            System.out.println("Server says: " + in.readLine());
        }
        while (!userInput.equals("Bye"));

        // close everything
        echoSocket.close();
        in.close();
        stdIn.close();
    }
}

Thanks!


Solution

  • The hint given by the teacher was that the chat room server only accepts the client when the client attempts to send a message. This homework is supposed to be done without using threads.

    The hint given by the teacher doesn't make sense. The client has to connect, then the server accepts. The client can't send a message without connecting first. Maybe the teacher really means that the client shouldn't connect until he has something to send?

    Following the hint given, I tried to create unbound ServerSocket and Socket in both the client and the server code. The key idea is that when the client attemps to send a message to the server, the client code would connect the unbound Socket, which will then trigger the server to connect the unbound ServerSocket and to accept the client.

    But that won't happen. It's impossible. If you try to connect to a port that isn't listening, you will get a ConnectException. The only way to put the port into listening state is to bind the ServerSocket. There is no magical back-door by which the server can possibly know that the client wants to connect so it should now do the bind.

    This homework is supposed to be done without using threads.

    Impossible to 'create a chat room where multiple clients can talk freely' that way, unless you are expected to use non-blocking I/O, or abuse the available() facility, or use a connection per message, but then I don't see how you can communicate one client's messages to the other clients, unless you're allowed to batch them up.

    There are too many imponderable aspects of this assignment as you have described it. The question as posed doesn't actully make sense, and your proposed solution certainly doesn't. You should just go ahead and write your program the normal way, with a connect, an accept, and some I/O. Get it working while your teacher comes up with a clarification.