Implement Chat CLI Client

In the ChatClient.initChatStream(), call chatStreamService.chat(…): and assign it to this.toServer variable.

public void initChatStream() {
  this.toServer = chatStreamService.chat(
      new StreamObserver<ChatMessageFromServer>() {
    @Override
    public void onNext(ChatMessageFromServer chatMessageFromServer) {
    }

    @Override
    public void onError(Throwable throwable) {
    }

    @Override
    public void onCompleted() {
    }
  });
}

When the chat messages arrive from the server, onNext will be called. Print out the message.

@Override
 public void onNext(ChatMessageFromServer chatMessageFromServer) {
   try {
     printLine(console, String.format("\n%tr %s> %s",
             chatMessageFromServer.getTimestamp().getSeconds(),
             chatMessageFromServer.getFrom(),
             chatMessageFromServer.getMessage()));

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

When the server throws an error or close the connection, shutdown the client:

@Override
public void onError(Throwable throwable) {
  logger.log(Level.SEVERE, "gRPC error", throwable);
  shutdown();
}

@Override
public void onCompleted() {
  logger.severe("server closed connection, shutting down...");
  shutdown();
}

Finally, implement ChatClient.sendMessage(…) method. Every time a user presses enter, it’ll call this method to send the message out to the server:

  1. Check that toServer observer is not null
  2. Then, call toServer.onNext(…) to send the message to the server to be broadcasted to the room
private void sendMessage(String room, String message) {
  logger.info("sending chat message");
  if (toServer == null) {
    logger.severe("Not connected");
  }

  toServer.onNext(ChatMessage.newBuilder()
      .setType(MessageType.TEXT)
      .setRoomName(room)
      .setMessage(message)
      .build());
}

Run the Chat Client

Run the chat client in multiple terminal windows. You must first create a chat room for the clients to connect into. This is done with the create command.

In one terminal window:

$ cd chat-cli-client
$ mvn install exec:java
...
STATE: CurrentState(STARTED,,,)
/login [username] | /quit
-> /login admin
[run-main-0] INFO ChatClient - processing login user
password> admin
...
admin-> /create beta
Jun 25, 2018 12:41:15 AM com.example.chat.ChatClient createRoom
INFO: create room: beta
admin-> /join beta
Jun 25, 2018 12:41:18 AM com.example.chat.ChatClient joinRoom
INFO: joinining room: beta

In another terminal window:

$ cd chat-cli-client
$ mvn install exec:java
...
STATE: CurrentState(STARTED,,,)
/login [username] | /quit
-> /login hydro
[run-main-0] INFO ChatClient - processing login user
password> hydro
...
hydro-> /join beta
...
hydro

Back in the first terminal window you should see:

hydro-> /join beta