一、服务端回传服务类 :
import java.io.ioexception; import java.io.inputstream; import java.io.outputStream; import java.net.socket; java.util.logging.level import; java.util.logging.logger import; 공개 클래스 Echoprotocol Imples untable {private static final int bufsize = 32; // I/O 버퍼 개인 소켓 ClientSocket의 크기 (바이트); // 소켓 클라이언트에 연결 개인 로거 로거; // Server Logger Public Echoprotocol (Socket Clientsocket, Logger Logger) {this.clientsocket = clientsocket; this.logger = 로거; } public static void hann outputStream out = clientSocket.getOutputStream (); int recvmsgsize; // 수신 된 메시지의 크기 int totalbytesechoed = 0; // 클라이언트 바이트에서받은 바이트 [] echobuffer = new Byte [bufsize]; // 클라이언트를 닫을 때까지 버퍼를 수신하십시오. TotalBytesechoed += recvmsgsize; } logger.info ( "client" + clientsocket.getRemotesocketAddress () + "," + TotalByTesechoed + "Bytes"); } catch (ioexception ex) {logger.log (레벨. 전조, "에코 프로토콜의 예외", ex); } 마침내 {try {clientsocket.close (); } catch (ioexception e) {}}} public void run () {handleEchoclient (this.clientsocket, this.logger); }}二、每个客户端请求都新启一个线程的 TCP p :
import java.io.ioexception; import java.net.serversocket; import java.net.socket; java.util.logging.logger import; public class tcpechoserverthread {public static void main (string [] args)은 ioexception {// 클라이언트 연결을 받아들이려면 서버 소켓을 만듭니다. Logger Logger = logger.getLogger ( "실제"); // 영원히 실행, 각 연결에 대한 스레드를 수락하고 스폰합니다. // 연결 대기중인 블록 // 새 연결 스레드 스레드 스레드 스레드 = 새 스레드 (New Echoprotocol (Clntsock, Logger)); thread.start (); logger.info ( "생성 및 시작 스레드" + 스레드 .getName ()); } / * 도달하지 않음 * /}}三、固定线程数的 TCP p :
import java.io.ioexception; import java.net.serversocket; import java.net.socket; java.util.logging.level import; java.util.logging.logger import; public class tcpechoserverpool {public static void main (string [] args)은 ioexception {int ridedpoolsize = 3; // 고정 된 ThreadPoolSize 최종 서버 소켓 SERVSOCK = New Serversocket (5500); 최종 로거 로거 = logger.getLogger ( "실용"); // (int i = 0; i <ThreadPoolsize; i ++) {strule stread = new Thread () {public void run () {while (true) {try {socket clntsock = servsock.accept (); // 연결을 기다립니다. choprotocol.handleechoclient (clntsock, logger); // handle} catch (ioException ex) {logger.log (level.warning, "client acccess lavening", ex); }}}}; thread.start (); logger.info ( "생성 및 시작 스레드 =" + 스레드 ()); }}}四、使用线程池 (스프링 使用)
1. : :
java.util.concurrent.*; /** * * * @Author Watson XU * @Since 1.0.0 <p> 2013-6-8 上午 10:33:09 </p> */public class threadpooltaskexecutor {private stridepooltaskexecutor () {} private static executorservice executor = executor = {) {newcachedthreadpool Callable runnable */runnable r) {receThread.setName; 공개 정적 무효 호출 (runnable task, timeUnit init, long timeout) timeoutException, runtimeexception {invoke (task, null, unit, timeout); } public static <t> t invoke (runnable task, t result, timeUnit init, long timeout) timeOutException, runtimeexception {future <T> future = executor.Submit (task, result); t t = null; try {t = future.get (타임 아웃, 단위); } catch (timeoutException e) {throw new timeoutException ( "스레드 타임 아웃 ..."); } catch (예외 e) {throw new runtimeexception (e); } return t; } public static <t> t invoke (Callable <T> 작업, 시간 유닛 단위, 긴 타임 아웃)는 TimeOutException, runtimeexception {// 这里将任务提交给执行器, 미래 <T> Future = Executor.Submit (태스크); // System.out.println ( "스레드에서 작업 부리"); t t = null; { / * * / /, 有了这个操作以后 * 1) 对 invoke () 的调用线程变成了等待任务完成状态 * 2) 主线程可以接收子线程的处理结果 * / t = future.get (timeout, unit); } catch (timeoutException e) {throw new timeoutException ( "스레드 타임 아웃 ..."); } catch (예외 e) {throw new runtimeexception (e); } return t; }}2. 服务端 TCP 具有伸缩性的 :
import java.io.ioexception; import java.net.serversocket; import java.net.socket; java.util.concurrent.timeUnit import; java.util.logging.logger import; import demo.callable.threadpooltaskexecutor; public class tcpechoserverexecutor {public static void main (string [] args)은 ioexception {// 클라이언트 연결 요청을 수락하기 위해 서버 소켓을 만듭니다. servsocket servsock = new serversocket (5500); Logger logger = logger.getLogger ( "실용"); // (true) {socket clntsock = servsock.accrect (); // 연결 대기 블록 //executorservice.submit(new echoprotocol (clntsock, logger)); try {ThreadPooltaskexecutor.invoke (New Echoprotocol (Clntsock, Logger), TimeUnit.seconds, 3); } catch (예외 e) {} //service.execute(new timelimitechopropotocol (clntsock, logger)); } / * 도달하지 않음 * /}}以上就是本文的全部内容 以上就是本文的全部内容, 查看更多 java 的语法, 大家可以关注 : 《Java에서 생각하는 사고 中文手册》、《 jdk 1.7 参考手册官方英文版》、《 jdk 1.6 API Java 中文参考手册》、《 JDK 1.5 API Java 中文参考手册》, 也希望大家多多支持武林网。