资源描述:
《java多线程—socket编程实例》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
多线程JavaSocket编程示例这篇做为学习孙卫琴<>的学习笔记吧.其中采用Java5的ExecutorService来进行线程池的方式实现多线程,模拟客户端多用户向同一服务器端发送请求.1.服务端package sterning;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.*;import java.util.concurrent.*;public class MultiThreadServer { private int port=8821; private ServerSocket serverSocket; private ExecutorService executorService;//线程池 private final int POOL_SIZE=10;//单个CPU线程池大小 public MultiThreadServer() throws IOException{ serverSocket=new ServerSocket(port); //Runtime的availableProcessor()方法返回当前系统的CPU数目. executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE); System.out.println("服务器启动"); }otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand public void service(){ while(true){ Socket socket=null; try { //接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接 socket=serverSocket.accept(); executorService.execute(new Handler(socket)); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws IOException { new MultiThreadServer().service(); }}class Handler implements Runnable{ private Socket socket; public Handler(Socket socket){ this.socket=socket; } private PrintWriter getWriter(Socket socket) throws IOException{ OutputStream socketOut=socket.getOutputStream(); return new PrintWriter(socketOut,true); }otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand private BufferedReader getReader(Socket socket) throws IOException{ InputStream socketIn=socket.getInputStream(); return new BufferedReader(new InputStreamReader(socketIn)); } public String echo(String msg){ return "echo:"+msg; } public void run(){ try { System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort()); BufferedReader br=getReader(socket); PrintWriter pw=getWriter(socket); String msg=null; while((msg=br.readLine())!=null){ System.out.println(msg); pw.println(echo(msg)); if(msg.equals("bye")) break; } } catch (IOException e) { e.printStackTrace(); }finally{ try { if(socket!=null) socket.close(); } catch (IOException e) { e.printStackTrace(); } }otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand }}2.客户端package sterning;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.Socket;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class MultiThreadClient { public static void main(String[] args) { int numTasks = 10; ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < numTasks; i++) { exec.execute(createTask(i)); } } // 定义一个简单的任务 private static Runnable createTask(final int taskID) { return new Runnable() {otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand private Socket socket = null; private int port=8821; public void run() { System.out.println("Task " + taskID + ":start"); try { socket = new Socket("localhost", port); // 发送关闭命令 OutputStream socketOut = socket.getOutputStream(); socketOut.write("shutdownr ".getBytes()); // 接收服务器的反馈 BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream())); String msg = null; while ((msg = br.readLine()) != null) System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } }; }}从而实现了多个客户端向服务器端发送请求,服务器端采用多线程的方式来处理的情况.再结合我之前的例子---Java基于Socket文件传输示例,就可以实现多线程文件的传输了otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand 评论# re:多线程JavaSocket编程示例 回复 更多评论 2007-11-1014:25byxiongzeng请问作者:可不可以利用服务端主动发信?# re:多线程JavaSocket编程示例 回复 更多评论 2007-12-0713:12byqifen膏药帖~~# re:多线程JavaSocket编程示例 回复 更多评论 2008-01-0722:19byjava综合网很好!不错!# re:多线程JavaSocket编程示例 回复 更多评论 2008-03-1411:36byfgfdgdgdfggfdgdf# re:多线程JavaSocket编程示例 回复 更多评论 2008-05-2817:14by钟侥我也是参照孙的书,可是运行不能得到正确的结果!很是郁闷啊[code]packagecom.zz.socket;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;publicclassEchoServer{privateintport=8000;privateServerSocketss;publicEchoServer()throwsIOException{otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand ss=newServerSocket(port);System.out.println("serverisstarting....");}privateStringechoString(Stringmsg){return"echo:"+msg;}publicstaticvoidmain(String[]args){try{newEchoServer().service();}catch(IOExceptione){e.printStackTrace();}}privatevoidservice(){while(true){Sockets=null;try{s=ss.accept();System.out.println("aclientiscoming......");BufferedReaderbr=this.getReader(s);PrintWriterpw=this.getWriter(s);Stringmsg=null;while((msg=br.readLine())!=null){System.out.println(msg);pw.println(this.echoString(msg)+" ");pw.flush();if(msg.equals("bye"))break;}otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand }catch(IOExceptione){}}}privatePrintWritergetWriter(Sockets)throwsIOException{returnnewPrintWriter(s.getOutputStream());}privateBufferedReadergetReader(Sockets)throwsIOException{returnnewBufferedReader(newInputStreamReader(s.getInputStream()));}}[/code]# re:多线程JavaSocket编程示例 回复 更多评论 2008-05-2817:15by钟侥packagecom.zz.socket;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;publicclassEchoClient{otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand privateStringhost="localhost";privateintport=8000;privateSocketsocket;privateEchoClient()throwsIOException{socket=newSocket(host,port);}publicvoidtalk()throwsIOException{try{BufferedReaderbr=getReader(socket);PrintWriterpw=getWriter(socket);BufferedReaderlocalReader=newBufferedReader(newInputStreamReader(System.in));Stringmsg=null;while((msg=localReader.readLine())!=null){pw.println(msg+" ");pw.flush();System.out.println(br.readLine());if(msg.equals("bye"))break;}}catch(IOExceptione){}finally{try{socket.close();}catch(IOExceptione){e.printStackTrace();}}otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand }privatePrintWritergetWriter(Sockets)throwsIOException{returnnewPrintWriter(s.getOutputStream());}privateBufferedReadergetReader(Sockets)throwsIOException{returnnewBufferedReader(newInputStreamReader(s.getInputStream()));}/***@paramargs*@throwsIOException*/publicstaticvoidmain(String[]args)throwsIOException{newEchoClient().talk();}}# re:多线程JavaSocket编程示例 回复 更多评论 2008-06-1623:04by有猫相伴的日子这个代码有很多问题,如请求处理,怎么封装请求对象,把请求对象放一队列从服务器端怎么发消息到客户端.....# re:多线程JavaSocket编程示例 回复 更多评论 2009-04-2710:22byfei貌似整体思想可以,但是,程序的问题就比较多了...# re:多线程JavaSocket编程示例[未登录] 回复 更多评论 2009-05-0715:38byjh第三方杀毒# re:多线程JavaSocket编程示例 回复 更多评论 otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand 2009-05-0717:14byOverKill如果多个线程对同一资源进行读取,能保证资源的原子性吗?应该对资源加锁# re:多线程JavaSocket编程示例 回复 更多评论 2009-05-1715:52by点水点点正找这样的文章多谢# re:多线程JavaSocket编程示例[未登录] 回复 更多评论 2009-08-2319:12byMark如何设定超时的问题呢?# re:多线程JavaSocket编程示例 回复 更多评论 2010-05-0913:48by诗特林fans我是java网络编程的初学者很想加诗特林为好友向你请教些问题。我的qq826463574# re:多线程JavaSocket编程示例 回复 更多评论 2010-05-0914:05by诗特林fans服务器端:publicclassMultiThreadServer{privateintport=8821;privateServerSocketserverSocket;privateExecutorServiceexecutorService;//线程池privatefinalintPOOL_SIZE=10;//单个CPU线程池大小publicMultiThreadServer()throwsIOException{serverSocket=newServerSocket(port);//Runtime的availableProcessor()方法返回当前系统的CPU数目.executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);System.out.println("服务器启动");}publicvoidservice(){while(true){Socketsocket=null;try{//接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand socket=serverSocket.accept();executorService.execute(newHandler(socket));}catch(Exceptione){e.printStackTrace();}}}publicstaticvoidmain(String[]args)throwsIOException{newMultiThreadServer().service();}}classHandlerimplementsRunnable{privateSocketsocket;publicHandler(Socketsocket){this.socket=socket;}/*privateDataOutputStreamdos(Socketsocket)throwsIOException{OutputStreamsocketOut=socket.getOutputStream();returnnewDataOutputStream(socketOut);}privateDataInputStreamdis(Socketsocket)throwsIOException{InputStreamsocketIn=socket.getInputStream();returnnewDataInputStream(socketIn);}*/publicvoidrun(){otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand try{System.out.println("Newconnectionaccepted"+socket.getInetAddress()+":"+socket.getPort());OutputStreamos=socket.getOutputStream();DataOutputStreamdos=newDataOutputStream(os);InputStreamis=socket.getInputStream();DataInputStreamdis=newDataInputStream(is);newmyserverread(dis).start();newmyserverwite(dos).start();}catch(IOExceptione){e.printStackTrace();}/*finally{try{if(socket!=null)socket.close();}catch(IOExceptione){e.printStackTrace();}}*/}}classmyserverreadextendsThread{privateDataInputStreamdis;publicmyserverread(DataInputStreamdis){this.dis=dis;}publicvoidrun(){Stringinfo;otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand try{while(true){info=dis.readUTF();System.out.println("对方说"+info);if(info.equals("bye")){System.out.println("对方下线,程序退出");System.exit(0);}}}catch(Exceptione){e.getStackTrace();}}}classmyserverwiteextendsThread{privateDataOutputStreamdos;publicmyserverwite(DataOutputStreamdos){this.dos=dos;}publicvoidrun(){BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));Stringinfo;try{while(true){info=br.readLine();dos.writeUTF(info);if(info.equals("bye")){System.out.println("自己下线,程序退出");otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand System.exit(0);}}}catch(Exceptione){e.getStackTrace();}}}# re:多线程JavaSocket编程示例 回复 更多评论 2010-05-0914:06by诗特林fans客户端:importjava.io.BufferedReader;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.net.Socket;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassMultiThreadClient{publicstaticvoidmain(String[]args){otherstaffoftheCentre.Duringthewar,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,ShenmufuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand intID=Info.i;ExecutorServiceexec=Executors.newCachedThreadPool();/*for(inti=0;i