欢迎来到天天文库
浏览记录
ID:51435926
大小:21.77 KB
页数:8页
时间:2020-03-24
《网络编程之多线程-7.docx》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Server:packagecom.socket_thread;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;publicclassServer{//定义保存所有Socket的ArrayList,并将其包装为线程安全的publicstaticListsocketList=Collectio
2、ns.synchronizedList(newArrayList());publicstaticvoidmain(String[]args){try{ServerSocketsocket=newServerSocket(3000);while(true){//代码会阻塞,将一直等待别人的连接Sockets=socket.accept();socketList.add(s);newThread(newServerThread(s)).start();}}catch(IOExceptione){//TODOAuto-generatedcatch
3、blocke.printStackTrace();}}}serverThread:packagecom.socket_thread;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintStream;importjava.net.Socket;publicclassServerThreadimplementsRunnable{//定义当前线程所处理的SocketSockets=null;Buffere
4、dReaderbr=null;publicServerThread(Sockets){this.s=s;//初始化该Socket对应的输出流try{br=newBufferedReader(newInputStreamReader(s.getInputStream()));}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubStringcontent=nu
5、ll;//采用循环不断从Socket中读取客户端发送过来的数据while((content=readFormClient())!=null){//遍历socketList中的每个Socket,将内容向每个Socket发送一次for(Sockets:Server.socketList){try{PrintStreamps=newPrintStream(s.getOutputStream());ps.println(content);}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackT
6、race();}}}}/***定义读取客户端数据方法*@return*/privateStringreadFormClient(){try{returnbr.readLine();//如果捕获异常,则表明该Socket对应的客户端已经关闭}catch(IOExceptione){//删除该SocketServer.socketList.remove(s);}returnnull;}}Client:packagecom.socket_thread;importjava.io.BufferedReader;importjava.io.IOException;i
7、mportjava.io.InputStreamReader;importjava.io.PrintStream;importjava.net.Socket;importjava.net.UnknownHostException;publicclassClient{publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubtry{Socketsocket=newSocket("127.0.0.1",3000);//客户端启动ClientThread线程不断的读取来自服务器的数据newT
8、hread(newClientThread(socket)).st
此文档下载收益归作者所有