java中使用多线程实现多服务功能

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

importjava.io.*;importjava.net.*;importjava.util.*;classmoreServer{publicstaticvoidmain(String[]args)throwsIOException{System.out.println(Serverstarting...\n);//使用8000端口提供服务ServerSocketserver=newServerSocket(8000);while(true){//阻塞,直到有客户连接Socketsk=server.accept();System.out.println(AcceptingConnection...\n);//启动服务线程newServerThread(sk).start();}}}//使用线程,为多个客户端服务classServerThreadextendsThread{privateSocketsk;ServerThread(Socketsk){this.sk=sk;}//线程运行实体publicvoidrun(){BufferedReaderin=null;PrintWriterout=null;try{InputStreamReaderisr;isr=newInputStreamReader(sk.getInputStream());in=newBufferedReader(isr);out=newPrintWriter(newBufferedWriter(newOutputStreamWriter(sk.getOutputStream())),true);while(true){//接收来自客户端的请求,根据不同的命令返回不同的信息。Stringcmd=in.readLine();System.out.println(cmd);if(cmd==null)break;cmd=cmd.toUpperCase();if(cmd.startsWith(BYE)){out.println(BYE);break;}else{out.println(你好,我是服务器!);}}}catch(IOExceptione){System.out.println(e.toString());}finally{System.out.println(ClosingConnection...\n);//最后释放资源try{if(in!=null)in.close();if(out!=null)out.close();if(sk!=null)sk.close();}catch(IOExceptione){System.out.println(closeerr+e);}}}}/********************************SocketClient.java************************************/importjava.io.*;importjava.net.*;classSocketThreadClientextendsThread{publicstaticintcount=0;//构造器,实现服务publicSocketThreadClient(InetAddressaddr){count++;BufferedReaderin=null;PrintWriterout=null;Socketsk=null;try{//使用8000端口sk=newSocket(addr,8000);InputStreamReaderisr;isr=newInputStreamReader(sk.getInputStream());in=newBufferedReader(isr);//建立输出out=newPrintWriter(newBufferedWriter(newOutputStreamWriter(sk.getOutputStream())),true);//向服务器发送请求System.out.println(count:+count);out.println(Hello);System.out.println(in.readLine());out.println(BYE);System.out.println(in.readLine());}catch(IOExceptione){System.out.println(e.toString());}finally{out.println(END);//释放资源try{if(in!=null)in.close();if(out!=null)out.close();if(sk!=null)sk.close();}catch(IOExceptione){}}}}//客户端publicclassSocketClient{publicstaticvoidmain(String[]args)throwsIOException,InterruptedException{InetAddressaddr=InetAddress.getByName(null);for(inti=0;i10;i++)newSocketThreadClient(addr);Thread.currentThread().sleep(1000);}}

1 / 4
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功