javaserver源代码文档格式.docx
《javaserver源代码文档格式.docx》由会员分享,可在线阅读,更多相关《javaserver源代码文档格式.docx(19页珍藏版)》请在冰豆网上搜索。
![javaserver源代码文档格式.docx](https://file1.bdocx.com/fileroot1/2022-11/25/fbf53be0-eb16-4e61-b630-94a9ec9b71be/fbf53be0-eb16-4e61-b630-94a9ec9b71be1.gif)
*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