Java 소켓 프로그래밍 예제-TCP 서버 스레드 풀
1. 서버 반환 서비스 유형:
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 서버:
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:
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. 스레드 풀 사용(Spring을 사용하는 스레드는 대기열, 최대 스레드 수, 최소 스레드 수 및 시간 제한 개념을 갖습니다.)
1. 스레드 풀 도구 클래스:
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. 확장 가능한 Tcp 서버:
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 */ } }
더 많은 Java 소켓 프로그래밍 예제 - TCP 서버 스레드 풀 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.
