欢迎来到天天文库
浏览记录
ID:17228078
大小:61.50 KB
页数:8页
时间:2018-08-28
《运用java的concurrent.executorservice线程池实现socket的tcp和udp连接》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、运用JAVA的concurrent.ExecutorService线程池实现socket的TCP和UDP连接最近在项目中可能要用到socket相关的东西来发送消息,所以初步研究了下socket的TCP和UDP实现方式,并且结合java1.5的concurrent.ExecutorService类来实现多线程。具体实现方式见代码:一、TCP方式:1、服务端实现方式:TCP的服务端实现方式主要用到ServerSocket类,接收等待客户端连接的方法是accept();代码如下:类SocketServerTCP1priv
2、ateintport=8823;2privateServerSocketserverSocket;3privateExecutorServiceexecutorService;//线程池4privatefinalintPOOL_SIZE=100;//单个CPU线程池大小56publicSocketServerTCP(){7try{8serverSocket=newServerSocket(port);9executorService=Executors.newFixedThreadPool(Runtime.getR
3、untime()10.availableProcessors()*POOL_SIZE);11logger.info("端口号为"+port+"的服务器启动");12}catch(IOExceptione){13e.printStackTrace();14}15}1617publicvoidservice(){18System.out.println("socket初始化成功!");19logger.info("socket服务端初始化成功!");20while(true){21Socketsocket=null;2
4、2try{23//接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitt
5、eeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand24socket=serverSocket.accept();25
6、executorService.execute(newCallService(socket));26}catch(Exceptione){27e.printStackTrace();28}29}30} CallService类主要作用是接收到消息后,来实现具体业务。代码如下:1/**2*功能说明:执行具体业务的线程3*/4classCallServiceimplementsRunnable{5Loggerlogger=Logger.getLogger(CallService.class);6privateSocke
7、tsocket;78privateBufferedReaderis;9privatePrintWriteros;1011publicCallService(Socketsocket){12this.socket=socket;13}1415publicvoidrun(){16try{17is=newBufferedReader(newInputStreamReader(socket.getInputStream()));18os=newPrintWriter(socket.getOutputStream());19
8、20Stringmsg=is.readLine();2122System.out.println("接到客户端消息"+msg);2324//返回消息给客户端25StringresponseMsg="服务端返回消息:"+msg;26os.println(responseMsg);27os.flush();28}catch(IOExceptione){other
此文档下载收益归作者所有