Commit 0cf041b8 authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Still having trouble with the chat client. The problem is that the...

[Ch15] Still having trouble with the chat client. The problem is that the server will read the whole buffer, even if the new message is shorter than what's in the buffer
parent 1f2af66f
Loading
Loading
Loading
Loading
+1 −1
Changes for src/main/java/ch15/DailyAdviceServer.java: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -23,7 +23,7 @@ public class DailyAdviceServer {
      InetSocketAddress address = new InetSocketAddress("localhost", 4242);
      serverSocketChannel.bind(address);

      while (true) {
      while (serverSocketChannel.isOpen()) {
        SocketChannel socketChannel = serverSocketChannel.accept();

        String advice = getAdvice();
+3 −1
Changes for src/main/java/ch15/SimpleChatClient.java: 3 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -70,10 +70,12 @@ class ClientUI {
    }

    public void actionPerformed(ActionEvent ev) {
      // pretty sure this is doing what I think it's doing
      byte[] message = outgoing.getText().getBytes();
      ByteBuffer buffer = ByteBuffer.wrap(message);
      try {
        channel.write(buffer);
        buffer.clear();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
@@ -101,11 +103,11 @@ class IncomingReader implements Runnable {

    try {
      while (channel.isOpen()) {
        buffer.clear();
        channel.read(buffer);
        String message = new String(buffer.array()).trim();
        System.out.println("read " + message);
        incomingMessageArea.append(message + "\n");
        buffer.clear();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
+4 −4
Changes for src/main/java/ch15/SimpleChatServer.java: 4 added lines, 4 removed lines.
Original line number Diff line number Diff line
package ch15;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
@@ -29,7 +30,7 @@ public class SimpleChatServer {
      }
      serverSocketChannel.close();
      executorService.shutdown();
    } catch (Exception ex) {
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
@@ -49,9 +50,7 @@ class ClientHandler implements Runnable {
    try {
      while (clientSocket.isOpen()) {
        clientSocket.read(buffer);
        String message = new String(buffer.array()).trim();
        System.out.println("read " + message);

        System.out.println("received: " + new String(buffer.array()).trim());
        buffer.flip();
        broadcaster.tellEveryone(buffer);
        buffer.clear();
@@ -79,5 +78,6 @@ class Broadcaster {
        ex.printStackTrace();
      }
    }
    message.flip();
  }
}
 No newline at end of file