search
HomeJavajavaTutorialJava Socket Programming Example-TCP Server Thread Pool

1. Server return service class:

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.Socket; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
  
public class EchoProtocol implements Runnable { 
  private static final int BUFSIZE = 32; // Size (in bytes) of I/O buffer 
  private Socket clientSocket; // Socket connect to client 
  private Logger logger; // Server logger 
  
  public EchoProtocol(Socket clientSocket, Logger logger) { 
    this.clientSocket = clientSocket; 
    this.logger = logger; 
  } 
  
  public static void handleEchoClient(Socket clientSocket, Logger logger) { 
    try { 
      // Get the input and output I/O streams from socket 
      InputStream in = clientSocket.getInputStream(); 
      OutputStream out = clientSocket.getOutputStream(); 
  
      int recvMsgSize; // Size of received message 
      int totalBytesEchoed = 0; // Bytes received from client 
      byte[] echoBuffer = new byte[BUFSIZE]; // Receive Buffer 
      // Receive until client closes connection, indicated by -1 
      while ((recvMsgSize = in.read(echoBuffer)) != -1) { 
        out.write(echoBuffer, 0, recvMsgSize); 
        totalBytesEchoed += recvMsgSize; 
      } 
  
      logger.info("Client " + clientSocket.getRemoteSocketAddress() + ", echoed " + totalBytesEchoed + " bytes."); 
        
    } catch (IOException ex) { 
      logger.log(Level.WARNING, "Exception in echo protocol", ex); 
    } finally { 
      try { 
        clientSocket.close(); 
      } catch (IOException e) { 
      } 
    } 
  } 
  
  public void run() { 
    handleEchoClient(this.clientSocket, this.logger); 
  } 
}

2. Tcp server that starts a new thread for each client request:

import java.io.IOException; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.logging.Logger; 
  
public class TCPEchoServerThread { 
  
  public static void main(String[] args) throws IOException { 
    // Create a server socket to accept client connection requests 
    ServerSocket servSock = new ServerSocket(5500); 
  
    Logger logger = Logger.getLogger("practical"); 
  
    // Run forever, accepting and spawning a thread for each connection 
    while (true) { 
      Socket clntSock = servSock.accept(); // Block waiting for connection 
      // Spawn thread to handle new connection 
      Thread thread = new Thread(new EchoProtocol(clntSock, logger)); 
      thread.start(); 
      logger.info("Created and started Thread " + thread.getName()); 
    } 
    /* NOT REACHED */
  } 
}

3. Tcp with fixed number of threads Server:

import java.io.IOException; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
  
public class TCPEchoServerPool { 
  public static void main(String[] args) throws IOException { 
    int threadPoolSize = 3; // Fixed ThreadPoolSize 
  
    final ServerSocket servSock = new ServerSocket(5500); 
    final Logger logger = Logger.getLogger("practical"); 
  
    // Spawn a fixed number of threads to service clients 
    for (int i = 0; i < threadPoolSize; i++) { 
      Thread thread = new Thread() { 
        public void run() { 
          while (true) { 
            try { 
              Socket clntSock = servSock.accept(); // Wait for a connection 
              EchoProtocol.handleEchoClient(clntSock, logger); // Handle it 
            } catch (IOException ex) { 
              logger.log(Level.WARNING, "Client accept failed", ex); 
            } 
          } 
        } 
      }; 
      thread.start(); 
      logger.info("Created and started Thread = " + thread.getName()); 
    } 
  } 
}

4. Use thread pool (threads using Spring will have the concepts of queue, maximum number of threads, minimum number of threads and timeout time)

1. Thread pool tool class :

import java.util.concurrent.*; 
  
/** 
 * 任务执行者 
 * 
 * @author Watson Xu 
 * @since 1.0.0 <p>2013-6-8 上午10:33:09</p> 
 */
public class ThreadPoolTaskExecutor { 
  
  private ThreadPoolTaskExecutor() { 
  
  } 
  
  private static ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { 
    int count; 
  
    /* 执行器会在需要自行任务而线程池中没有线程的时候来调用该程序。对于callable类型的调用通过封装以后转化为runnable */ 
    public Thread newThread(Runnable r) { 
      count++; 
      Thread invokeThread = new Thread(r); 
      invokeThread.setName("Courser Thread-" + count); 
      invokeThread.setDaemon(false);// //???????????? 
  
      return invokeThread; 
    } 
  }); 
  
  public static void invoke(Runnable task, TimeUnit unit, long timeout) throws TimeoutException, RuntimeException { 
    invoke(task, null, unit, timeout); 
  } 
  
  public static <T> T invoke(Runnable task, T result, TimeUnit unit, long timeout) throws TimeoutException, 
      RuntimeException { 
    Future<T> future = executor.submit(task, result); 
    T t = null; 
    try { 
      t = future.get(timeout, unit); 
    } catch (TimeoutException e) { 
      throw new TimeoutException("Thread invoke timeout ..."); 
    } catch (Exception e) { 
      throw new RuntimeException(e); 
    } 
    return t; 
  } 
  
  public static <T> T invoke(Callable<T> task, TimeUnit unit, long timeout) throws TimeoutException, RuntimeException { 
    // 这里将任务提交给执行器,任务已经启动,这里是异步的。 
    Future<T> future = executor.submit(task); 
    // System.out.println("Task aready in thread"); 
    T t = null; 
    try { 
      /* 
       * 这里的操作是确认任务是否已经完成,有了这个操作以后 
       * 1)对invoke()的调用线程变成了等待任务完成状态 
       * 2)主线程可以接收子线程的处理结果 
       */
      t = future.get(timeout, unit); 
    } catch (TimeoutException e) { 
      throw new TimeoutException("Thread invoke timeout ..."); 
    } catch (Exception e) { 
      throw new RuntimeException(e); 
    } 
  
    return t; 
  } 
}

2. Scalable Tcp server:

import java.io.IOException; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.concurrent.TimeUnit; 
import java.util.logging.Logger; 
  
import demo.callable.ThreadPoolTaskExecutor; 
  
  
public class TCPEchoServerExecutor { 
  
  public static void main(String[] args) throws IOException { 
    // Create a server socket to accept client connection requests 
    ServerSocket servSock = new ServerSocket(5500); 
  
    Logger logger = Logger.getLogger("practical"); 
      
    // Run forever, accepting and spawning threads to service each connection 
    while (true) { 
      Socket clntSock = servSock.accept(); // Block waiting for connection 
      //executorService.submit(new EchoProtocol(clntSock, logger)); 
      try { 
        ThreadPoolTaskExecutor.invoke(new EchoProtocol(clntSock, logger), TimeUnit.SECONDS, 3); 
      } catch (Exception e) { 
      }  
      //service.execute(new TimelimitEchoProtocol(clntSock, logger)); 
    } 
    /* NOT REACHED */
  } 
}

For more Java Socket programming examples - TCP server thread pool related articles, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool