Commit ff5d6452 authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] SimpleChatServer uses a thread pool, but probably it doesn't need to...

[Ch15] SimpleChatServer uses a thread pool, but probably it doesn't need to since it's a good example of something that _could_ do manual Thread creation (but then show how it's supposed to be done)
parent 4ca3d4ed
Loading
Loading
Loading
Loading
+4 −4
Changes for src/main/java/ch15/SimpleChatClient.java: 4 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -20,10 +20,6 @@ public class SimpleChatClient {
  private BufferedReader reader;
  private PrintWriter writer;

  public static void main(String[] args) {
    new SimpleChatClient().go();
  }

  public void go() {
    incoming = new JTextArea(15, 50);
    incoming.setLineWrap(true);
@@ -89,4 +85,8 @@ public class SimpleChatClient {
      }
    }
  }

  public static void main(String[] args) {
    new SimpleChatClient().go();
  }
}
 No newline at end of file
+6 −4
Changes for src/main/java/ch15/SimpleChatServer.java: 6 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,8 @@ import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleChatServer {
  ArrayList<Writer> clientOutputStreams;
@@ -18,16 +20,16 @@ public class SimpleChatServer {

  public void go() {
    clientOutputStreams = new ArrayList<>();
    ExecutorService threadPool = Executors.newFixedThreadPool(5);
    try {
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.bind(new InetSocketAddress("localhost", 5000));
      serverSocketChannel.bind(new InetSocketAddress(5000));

      while (true) {
      while (serverSocketChannel.isOpen()) {
        SocketChannel clientSocket = serverSocketChannel.accept();
        Writer writer = Channels.newWriter(clientSocket, StandardCharsets.UTF_8);
        clientOutputStreams.add(writer);
        Thread t = new Thread(new ClientHandler(clientSocket));
        t.start();
        threadPool.submit(new ClientHandler(clientSocket));
        System.out.println("got a connection");
      }
    } catch (Exception ex) {