java多线程—Socket编程实例.docx

上传人:asd****56 文档编号:70332633 上传时间:2023-01-19 格式:DOCX 页数:19 大小:37.72KB
返回 下载 相关 举报
java多线程—Socket编程实例.docx_第1页
第1页 / 共19页
java多线程—Socket编程实例.docx_第2页
第2页 / 共19页
点击查看更多>>
资源描述

《java多线程—Socket编程实例.docx》由会员分享,可在线阅读,更多相关《java多线程—Socket编程实例.docx(19页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、多线程Java Socket编程示例这篇做为学习孙卫琴的学习笔记吧.其中采用Java 5的ExecutorService来进行线程池的方式实现多线程,模拟客户端多用户向同一服务器端发送请求.1.服务端packagesterning;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.io.PrintWriter;import.*;importjav

2、a.util.concurrent.*;publicclassMultiThreadServerprivateintport=8821;privateServerSocketserverSocket;privateExecutorServiceexecutorService;/线程池privatefinalintPOOL_SIZE=10;/单个CPU线程池大小publicMultiThreadServer()throwsIOExceptionserverSocket=newServerSocket(port);/Runtime的availableProcessor()方法返回当前系统的CPU数

3、目.executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);System.out.println(服务器启动);publicvoidservice()while(true)Socketsocket=null;try/接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接socket=serverSocket.accept();executorService.execute(newHandler(socket);catch(Excepti

4、one)e.printStackTrace();publicstaticvoidmain(Stringargs)throwsIOExceptionnewMultiThreadServer().service();classHandlerimplementsRunnableprivateSocketsocket;publicHandler(Socketsocket)this.socket=socket;privatePrintWritergetWriter(Socketsocket)throwsIOExceptionOutputStreamsocketOut=socket.getOutputSt

5、ream();returnnewPrintWriter(socketOut,true);privateBufferedReadergetReader(Socketsocket)throwsIOExceptionInputStreamsocketIn=socket.getInputStream();returnnewBufferedReader(newInputStreamReader(socketIn);publicStringecho(Stringmsg)returnecho:+msg;publicvoidrun()trySystem.out.println(Newconnectionacc

6、epted+socket.getInetAddress()+:+socket.getPort();BufferedReaderbr=getReader(socket);PrintWriterpw=getWriter(socket);Stringmsg=null;while(msg=br.readLine()!=null)System.out.println(msg);pw.println(echo(msg);if(msg.equals(bye)break;catch(IOExceptione)e.printStackTrace();finallytryif(socket!=null)socke

7、t.close();catch(IOExceptione)e.printStackTrace();2.客户端packagesterning;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.OutputStream;import.Socket;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;publicclassMultiThread

8、Clientpublicstaticvoidmain(Stringargs)intnumTasks=10;ExecutorServiceexec=Executors.newCachedThreadPool();for(inti=0;inumTasks;i+)exec.execute(createTask(i);/定义一个简单的任务privatestaticRunnablecreateTask(finalinttaskID)returnnewRunnable()privateSocketsocket=null;privateintport=8821;publicvoidrun()System.o

9、ut.println(Task+taskID+:start);trysocket=newSocket(localhost,port);/发送关闭命令OutputStreamsocketOut=socket.getOutputStream();socketOut.write(shutdownrn.getBytes();/接收服务器的反馈BufferedReaderbr=newBufferedReader(newInputStreamReader(socket.getInputStream();Stringmsg=null;while(msg=br.readLine()!=null)System.

10、out.println(msg);catch(IOExceptione)e.printStackTrace();从而实现了多个客户端向服务器端发送请求,服务器端采用多线程的方式来处理的情况.再结合我之前的例子-Java基于Socket文件传输示例,就可以实现多线程文件的传输了 评论#re: 多线程Java Socket编程示例回复更多评论 2007-11-10 14:25 by xiongzeng 请问作者: 可不可以利用服务端主动发信?#re: 多线程Java Socket编程示例回复更多评论 2007-12-07 13:12 by qifen 膏药帖#re: 多线程Java Socket编

11、程示例回复更多评论 2008-01-07 22:19 by java综合网 很好!不错!#re: 多线程Java Socket编程示例回复更多评论 2008-03-14 11:36 by fgfdg dgdfggfdgdf#re: 多线程Java Socket编程示例回复更多评论 2008-05-28 17:14 by 钟侥 我也是参照孙的书,可是运行不能得到正确的结果!很是郁闷啊 code package com.zz.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.Input

12、StreamReader; import java.io.PrintWriter; import .ServerSocket; import .Socket; public class EchoServer private int port = 8000; private ServerSocket ss; public EchoServer() throws IOException ss = new ServerSocket(port); System.out.println(server is starting.); private String echoString(String msg)

13、 return echo: + msg; public static void main(String args) try new EchoServer().service(); catch (IOException e) e.printStackTrace(); private void service() while(true) Socket s = null; try s = ss.accept(); System.out.println(a client is coming.); BufferedReader br = this.getReader(s); PrintWriter pw

14、 = this.getWriter(s); String msg = null; while(msg = br.readLine() != null) System.out.println(msg); pw.println(this.echoString(msg)+n); pw.flush(); if(msg.equals(bye) break; catch(IOException e ) private PrintWriter getWriter(Socket s) throws IOException return new PrintWriter(s.getOutputStream();

15、private BufferedReader getReader(Socket s) throws IOException return new BufferedReader(new InputStreamReader(s.getInputStream(); /code#re: 多线程Java Socket编程示例回复更多评论 2008-05-28 17:15 by 钟侥 package com.zz.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRead

16、er; import java.io.PrintWriter; import .Socket; public class EchoClient private String host = localhost; private int port = 8000; private Socket socket; private EchoClient() throws IOException socket = new Socket(host, port); public void talk() throws IOException try BufferedReader br = getReader(so

17、cket); PrintWriter pw = getWriter(socket); BufferedReader localReader = new BufferedReader( new InputStreamReader(System.in); String msg = null; while (msg = localReader.readLine()!= null) pw.println(msg+n); pw.flush(); System.out.println(br.readLine(); if (msg.equals(bye) break; catch (IOException

18、e) finally try socket.close(); catch (IOException e) e.printStackTrace(); private PrintWriter getWriter(Socket s) throws IOException return new PrintWriter(s.getOutputStream(); private BufferedReader getReader(Socket s) throws IOException return new BufferedReader(new InputStreamReader(s.getInputStr

19、eam(); /* * param args * throws IOException */ public static void main(String args) throws IOException new EchoClient().talk(); #re: 多线程Java Socket编程示例回复更多评论 2008-06-16 23:04 by 有猫相伴的日子 这个代码有很多问题,如请求处理,怎么封装请求对象,把请求对象放一队列 从服务器端怎么发消息到客户端. #re: 多线程Java Socket编程示例回复更多评论 2009-04-27 10:22 by fei 貌似整体思想可以,

20、但是,程序的问题就比较多了.#re: 多线程Java Socket编程示例未登录回复更多评论 2009-05-07 15:38 by jh 第三方杀毒#re: 多线程Java Socket编程示例回复更多评论 2009-05-07 17:14 by OverKill 如果多个线程对同一资源进行读取,能保证资源的原子性吗?应该对资源加锁#re: 多线程Java Socket编程示例回复更多评论 2009-05-17 15:52 by 点水点点 正找这样的文章 多谢#re: 多线程Java Socket编程示例未登录回复更多评论 2009-08-23 19:12 by Mark 如何设定超时的问题

21、呢?#re: 多线程Java Socket编程示例回复更多评论 2010-05-09 13:48 by 诗特林fans 我是java网络编程的初学者很想加 诗特林 为好友向你请教些问题。我的qq826463574#re: 多线程Java Socket编程示例回复更多评论 2010-05-09 14:05 by 诗特林fans 服务器端: public class MultiThreadServer private int port=8821; private ServerSocket serverSocket; private ExecutorService executorService;/

22、线程池 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(服务器启动)

23、; 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().servic

24、e(); class Handler implements Runnable private Socket socket; public Handler(Socket socket) this.socket=socket; /*private DataOutputStream dos(Socket socket) throws IOException OutputStream socketOut=socket.getOutputStream(); return new DataOutputStream(socketOut); private DataInputStream dis(Socket

25、 socket) throws IOException InputStream socketIn=socket.getInputStream(); return new DataInputStream(socketIn); */ public void run() try System.out.println(New connection accepted +socket.getInetAddress()+:+socket.getPort(); OutputStream os = socket.getOutputStream(); DataOutputStream dos = new Data

26、OutputStream(os); InputStream is = socket.getInputStream( ); DataInputStream dis=new DataInputStream(is); new myserverread(dis).start(); new myserverwite(dos).start(); catch (IOException e) e.printStackTrace(); /*finally try if(socket!=null) socket.close(); catch (IOException e) e.printStackTrace();

27、 */ class myserverread extends Thread private DataInputStream dis; public myserverread (DataInputStream dis) this.dis=dis; public void run() String info; try while(true) info=dis.readUTF(); System.out.println(对方说+info); if (info.equals(bye) System.out.println(对方下线,程序退出); System.exit(0); catch (Excep

28、tion e)e.getStackTrace(); class myserverwite extends Thread private DataOutputStream dos; public myserverwite (DataOutputStream dos) this.dos=dos; public void run() BufferedReader br=new BufferedReader(new InputStreamReader(System.in); String info; try while(true) info=br.readLine(); dos.writeUTF(in

29、fo); if (info.equals(bye) System.out.println(自己下线,程序退出); System.exit(0); catch (Exception e)e.getStackTrace(); #re: 多线程Java Socket编程示例回复更多评论 2010-05-09 14:06 by 诗特林fans 客户端: import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; im

30、port java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import .Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiThreadClient public static void main(String args) int ID=Info.i; ExecutorService exec = Execu

31、tors.newCachedThreadPool(); /* for (int i = 0; i numTasks; i+) exec.execute(createTask(i); */ System.out.println(客户端线程+ID+已启动); exec.execute(createTask(ID); Info.i=ID+; / 定义一个简单的任务 private static Runnable createTask(int taskID) / this.taskID=taskID; return new Runnable() private Socket socket = null

32、; private int port=8821; public void run() / System.out.println(Task + taskID + :start); try socket = new Socket(localhost, port); / 发送关闭命令 InputStream is = socket.getInputStream( ); DataInputStream dis=new DataInputStream(is); OutputStream os = socket.getOutputStream(); DataOutputStream dos = new D

33、ataOutputStream(os); new myclientread(dis).start(); new myclientwite(dos).start(); catch (IOException e) e.printStackTrace(); ; class myclientread extends Thread private DataInputStream dis; public myclientread (DataInputStream dis) this.dis=dis; public void run() String info; try while(true) info=d

34、is.readUTF(); System.out.println(对方说+info); if (info.equals(bye) System.out.println(对方下线,程序退出); System.exit(0); catch (Exception e)e.getStackTrace(); class myclientwite extends Thread private DataOutputStream dos; public myclientwite (DataOutputStream dos) this.dos=dos; public void run() BufferedReader br=new BufferedReader(new InputStreamReader(System.in); String info; try while(true) info=br.readLine(); dos.writeUTF(info); if (info.equals(bye) System.out.println(自己下线,程序退出); System.exit(0); catch (Exception e) 这个程序我想实现多用户与服务器的连接交互问题,但是能过连接上但是不能实现交互,这是为什么呢?我是java网络编程初学者谢谢您的指教急待您的回复!

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 其他杂项

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁