javaserver源代码文档格式.docx

上传人:b****3 文档编号:16748955 上传时间:2022-11-25 格式:DOCX 页数:19 大小:21.64KB
下载 相关 举报
javaserver源代码文档格式.docx_第1页
第1页 / 共19页
javaserver源代码文档格式.docx_第2页
第2页 / 共19页
javaserver源代码文档格式.docx_第3页
第3页 / 共19页
javaserver源代码文档格式.docx_第4页
第4页 / 共19页
javaserver源代码文档格式.docx_第5页
第5页 / 共19页
点击查看更多>>
下载资源
资源描述

javaserver源代码文档格式.docx

《javaserver源代码文档格式.docx》由会员分享,可在线阅读,更多相关《javaserver源代码文档格式.docx(19页珍藏版)》请在冰豆网上搜索。

javaserver源代码文档格式.docx

*shouldbefollowedbyapasswordandport,andwillstartspecial

*servercontrolservicerunningonthespecifiedport,protectedbythe

*specifiedpassword.

publicstaticvoidmain(String[]args){

try{

if(args.length<

2)//Checknumberofarguments

thrownewIllegalArgumentException("

Mustspecifyaservice"

);

//CreateaServerobjectthatusesstandardoutasitslogand

//hasalimitoftenconcurrentconnectionsatonce.

Servers=newServer(System.out,10);

//Parsetheargumentlist

inti=0;

while(i<

args.length){

if(args[i].equals("

-control"

)){//Handlethe-controlarg

i++;

Stringpassword=args[i++];

intport=Integer.parseInt(args[i++]);

//addcontrolservice

s.addService(newControl(s,password),port);

}

else{

//Otherwisestartanamedserviceonthespecifiedport.

//DynamicallyloadandinstantiateaServiceclass

StringserviceName=args[i++];

ClassserviceClass=Class.forName(serviceName);

Serviceservice=(Service)serviceClass.newInstance();

s.addService(service,port);

}

catch(Exceptione){//Displayamessageifanythinggoeswrong

System.err.println("

Server:

"

+e);

Usage:

javaServer"

+"

[-control]"

[...]"

System.exit

(1);

//Thisisthestatefortheserver

Mapservices;

//HashtablemappingportstoListeners

Setconnections;

//Thesetofcurrentconnections

intmaxConnections;

//Theconcurrentconnectionlimit

ThreadGroupthreadGroup;

//Thethreadgroupforallourthreads

PrintWriterlogStream;

//Wherewesendourloggingoutputto

*ThisistheServer()constructor.Itmustbepassedastream

*tosendlogoutputto(maybenull),andthelimitonthenumberof

*concurrentconnections.

publicServer(OutputStreamlogStream,intmaxConnections){

setLogStream(logStream);

log("

Startingserver"

threadGroup=newThreadGroup(Server.class.getName());

this.maxConnections=maxConnections;

services=newHashMap();

connections=newHashSet(maxConnections);

/**

*Apublicmethodtosetthecurrentloggingstream.Passnull

*toturnloggingoff

publicsynchronizedvoidsetLogStream(OutputStreamout){

if(out!

=null)logStream=newPrintWriter(out);

elselogStream=null;

/**Writethespecifiedstringtothelog*/

protectedsynchronizedvoidlog(Strings){

if(logStream!

=null){

logStream.println("

["

+newDate()+"

]"

+s);

logStream.flush();

/**Writethespecifiedobjecttothelog*/

protectedvoidlog(Objecto){log(o.toString());

*Thismethodmakestheserverstartprovidinganewservice.

*ItrunsthespecifiedServiceobjectonthespecifiedport.

publicsynchronizedvoidaddService(Serviceservice,intport)

throwsIOException

{

Integerkey=newInteger(port);

//thehashtablekey

//Checkwhetheraserviceisalreadyonthatport

if(services.get(key)!

=null)

Port"

+port+

alreadyinuse."

//CreateaListenerobjecttolistenforconnectionsontheport

Listenerlistener=newListener(threadGroup,port,service);

//Storeitinthehashtable

services.put(key,listener);

//Logit

Startingservice"

+service.getClass().getName()+

onport"

+port);

//Startthelistenerrunning.

listener.start();

*Thismethodmakestheserverstopprovidingaserviceonaport.

*Itdoesnotterminateanypendingconnectionstothatservice,merely

*causestheservertostopacceptingnewconnections

publicsynchronizedvoidremoveService(intport){

//hashtablekey

//LookuptheListenerobjectfortheportinthehashtable

finalListenerlistener=(Listener)services.get(key);

if(listener==null)return;

//Askthelistenertostop

listener.pleaseStop();

//Removeitfromthehashtable

services.remove(key);

//Andlogit.

Stoppingservice"

+listener.service.getClass().getName()+

*ThisnestedThreadsubclassisa"

listener"

.Itlistensfor

*connectionsonaspecifiedport(usingaServerSocket)andwhenitgets

*aconnectionrequest,itcallstheserversaddConnection()methodto

*accept(orreject)theconnection.ThereisoneListenerforeach

*ServicebeingprovidedbytheServer.

publicclassListenerextendsThread{

ServerSocketlisten_socket;

//Thesockettolistenforconnections

intport;

//Theportwe'

relisteningon

Serviceservice;

//Theservicetoprovideonthatport

volatilebooleanstop=false;

//Whetherwe'

vebeenaskedtostop

*TheListenerconstructorcreatesathreadforitselfinthe

*threadgroup.ItcreatesaServerSockettolistenforconnections

*onthespecifiedport.ItarrangesfortheServerSockettobe

*interruptible,sothatservicescanberemovedfromtheserver.

publicListener(ThreadGroupgroup,intport,Serviceservice)

super(group,"

Listener:

"

listen_socket=newServerSocket(port);

//giveitanon-zerotimeoutsoaccept()canbeinterrupted

listen_socket.setSoTimeout(600000);

this.port=port;

this.service=service;

*ThisisthepolitewaytogetaListenertostopaccepting

*connections

***/

publicvoidpleaseStop(){

this.stop=true;

//Setthestopflag

this.interrupt();

//Stopblockinginaccept()

try{listen_socket.close();

}//Stoplistening.

catch(IOExceptione){}

*AListenerisaThread,andthisisitsbody.

*Waitforconnectionrequests,acceptthem,andpassthesocketon

*totheaddConnectionmethodoftheserver.

publicvoidrun(){

while(!

stop){//loopuntilwe'

reaskedtostop.

Socketclient=listen_socket.accept();

addConnection(client,service);

catch(InterruptedIOExceptione){}

catch(IOExceptione){log(e);

}

*ThisisthemethodthatListenerobjectscallwhentheyaccepta

*connectionfromaclient.IteithercreatesaConnectionobject

*fortheconnectionandaddsittothelistofcurrentconnections,

*or,ifthelimitonconnectionshasbeenreached,itclosesthe

*connection.

protectedsynchronizedvoidaddConnection(Sockets,Serviceservice){

//Iftheconnectionlimithasbeenreached

if(connections.size()>

=maxConnections){

//Thentelltheclientitisbeingrejected.

PrintWriterout=newPrintWriter(s.getOutputStream());

out.print("

Connectionrefused;

+

theserverisbusy;

pleasetryagainlater.\n"

out.flush();

//Andclosetheconnectiontotherejectedclient.

s.close();

//Andlogit,ofcourse

Connectionrefusedto"

s.getInetAddress().getHostAddress()+

:

+s.getPort()+"

maxconnectionsreached."

}catch(IOExceptione){log(e);

else{//Otherwise,ifthelimithasnotbeenreached

//CreateaConnectionthreadtohandlethisconnection

Connectionc=newConnection(s,service);

//Addittothelistofcurrentconnections

connections.add(c);

//Logthisnewconnection

Connectedto"

+s.getInetAddress().getHostAddress()+

+s.getLocalPort()+

forservice"

+service.getClass().getName());

//AndstarttheConnectionthreadtoprovidetheservice

c.start();

*AConnectionthreadcallsthismethodjustbeforeitexits.Itremoves

*thespecifiedConnectionfromthesetofconnections.

protectedsynchronizedvoidendConnection(Connectionc){

connections.remove(c);

Connectionto"

+c.client.getInetAddress().getHostAddress()+

+c.client.getPort()+"

closed."

/**Changethecurrentconnectionlimit*/

publicsynchronizedvoidsetMaxConnections(intmax){

maxConnections=max;

*Thismethoddisplaysstatusinformationabouttheserveronthe

*specifiedstream.Itcanbeusedfordebugging,andisusedbythe

*Controlservicelaterinthisexample.

publicsynchronizedvoiddisplayStatus(PrintWriterout){

//DisplayalistofallServicesthatarebeingprovided

Iteratorkeys=services.keySet().iterator();

while(keys.hasNext()){

Integerport=(Integer)keys.next();

Listenerlistener=(Listener)services.get(port);

SERVICE"

+listener.service.getClass().getName()

+"

ONPORT"

+port+"

\n"

//Display

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工程科技 > 能源化工

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1