`
holoblog
  • 浏览: 1264481 次
博客专栏
E0fcf0b7-6756-3051-9a54-90b4324c9940
SQL Server 20...
浏览量:19554
文章分类
社区版块
存档分类
最新评论

java安全机制其实有点不安全

 
阅读更多

看下面的这段代码,摘自《Java Examples in a Nutsbell》(java实例技术手册):

就是一个简单的通用的多线程服务器

这个例子可以通过配置参数:

java je3.net.Server -control www 3333 je3.net.Server$HTTPMirror 5555

来启动,然后再ie中输入: http://localhost:5555就可以看到效果。

写一个policy文件放在同根目录下:叫server.policy

grant{
permission java.net.SocketPermission "*:1024-4444","connect,accept";
permission java.io.FilePermission "E://workspace//j2ee1.3//-", "read";
};

下面加上jvm虚拟机参数

java -Djava.security.manager -Djava.security.policy=server.policy

je3.net.Server -control www 3333 je3.net.Server$HTTPMirror 5555再次启动。

按道理,本不应该启动。因为端口5555并没有得到连接许可。但是很可惜输入 http://localhost:5555还是可以看到结果。因为在java的sdk中暗含了java.policy文件。那就把它改为-Djava.security.policy==server.policy应该就可以了。结果跑不了了。原因就在policy文件中的permission java.net.SocketPermission "*:1024-4444","connect,accept";其实,我一直不太清楚listen ,accept,connect的区别在什么地方。但是这里的例子说明你只用permission java.net.SocketPermission "*:1024-4444","listen";就可以了。端口该闭的就闭了。如果用accept和connect反而没有什么用。不知道java的安全性高在什么地方。因为java.policy文件中从1024以上的端口全都使用了listen。所以以后要配置端口时一定要注意。

/**//*
*Copyright(c)2004DavidFlanagan.Allrightsreserved.
*ThiscodeisfromthebookJavaExamplesinaNutshell,3ndEdition.
*ItisprovidedAS-IS,WITHOUTANYWARRANTYeitherexpressedorimplied.
*Youmaystudy,use,andmodifyitforanynon-commercialpurpose,
*includingteachinganduseinopen-sourceprojects.
*Youmaydistributeitnon-commerciallyaslongasyouretainthisnotice.
*Foracommercialuselicense,ortopurchasethebook,
*pleasevisit
http://www.davidflanagan.com/javaexamples3.
*/

packageje3.net;
importjava.io.*;
importjava.net.*;
importjava.util.*;
importjava.util.logging.*;

/***//**
*Thisclassisagenericframeworkforaflexible,multi-threadedserver.
*Itlistensonanynumberofspecifiedports,and,whenitreceivesa
*connectiononaport,passesinputandoutputstreamstoaspecifiedService
*objectwhichprovidestheactualservice.Itcanlimitthenumberof
*concurrentconnections,andlogsactivitytoaspecifiedstream.
*
*/

publicclassServer...{
/***//**
*Amain()methodforrunningtheserverasastandaloneprogram.The
*command-lineargumentstotheprogramshouldbepairsofservicenames
*andportnumbers.Foreachpair,theprogramwilldynamicallyloadthe
*namedServiceclass,instantiateit,andtelltheservertoprovide
*thatServiceonthespecifiedport.Thespecial-controlargument
*shouldbefollowedbyapasswordandport,andwillstartspecial
*servercontrolservicerunningonthespecifiedport,protectedbythe
*specifiedpassword.
*
*/

publicstaticvoidmain(String[]args)...{
try...{
if(args.length<2)//Checknumberofarguments
thrownewIllegalArgumentException("Mustspecifyaservice");

//Createaserverobjectthathasalimitof10concurrent
//connections,andlogstoaLoggerattheLevel.INFOlevel
//PriortoJava1.4wedidthis:newServer(System.out,10);
Servers=newServer(Logger.getLogger(Server.class.getName()),
Level.INFO,
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();
intport=Integer.parseInt(args[i++]);
s.addService(service,port);
}

}

}

catch(Exceptione)...{//Displayamessageifanythinggoeswrong
System.err.println("Server:"+e);
System.err.println(
"Usage:javaServer"+
"[-control<password><port>]"+
"[<servicename><port>...]");
System.exit(
1);
}

}


//Thisisthestatefortheserver
Mapservices;//HashtablemappingportstoListeners
Setconnections;//Thesetofcurrentconnections
intmaxConnections;//Theconcurrentconnectionlimit
ThreadGroupthreadGroup;//Thethreadgroupforallourthreads

//Thisclasswasoriginallywrittentosendloggingoutputtoastream.
//Ithasbeenretrofittedtoalsosupportthejava.util.loggingAPIof
//Java1.4.Youcanuseeither,neither,orboth.
PrintWriterlogStream;//Wherewesendourloggingoutputto
Loggerlogger;//AJava1.4loggingdestination
LevellogLevel;//theleveltologmessagesat

/***//**
*ThisistheServer()constructor.Itmustbepassedastream
*tosendlogoutputto(maybenull),andthelimitonthenumberof
*concurrentconnections.
*
*/

publicServer(OutputStreamlogStream,intmaxConnections)...{
this(maxConnections);
setLogStream(logStream);
log(
"Startingserver");
}


/***//**
*ThisconstructoraddedtosupportloggingwiththeJava1.4Loggerclass
*
*/

publicServer(Loggerlogger,LevellogLevel,intmaxConnections)...{
this(maxConnections);
setLogger(logger,logLevel);
log(
"Startingserver");
}


/***//**
*Thisconstructorsupportsnologging
*
*/

publicServer(intmaxConnections)...{
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;
}


/***//**
*SetthecurrentLoggerandlogginglevel.Passnulltoturnloggingoff.
*
*/

publicsynchronizedvoidsetLogger(Loggerlogger,Levellevel)...{
this.logger=logger;
this.logLevel=level;
}


/***//**Writethespecifiedstringtothelog*/
protectedsynchronizedvoidlog(Strings)...{
if(logger!=null)logger.log(logLevel,s);
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)
thrownewIllegalArgumentException("Port"+port+
"alreadyinuse.");
//CreateaListenerobjecttolistenforconnectionsontheport
Listenerlistener=newListener(threadGroup,port,service);
//Storeitinthehashtable
services.put(key,listener);
//Logit
log("Startingservice"+service.getClass().getName()+
"onport"+port);
//Startthelistenerrunning.
listener.start();
}


/***//**
*Thismethodmakestheserverstopprovidingaserviceonaport.
*Itdoesnotterminateanypendingconnectionstothatservice,merely
*causestheservertostopacceptingnewconnections
*
*/

publicsynchronizedvoidremoveService(intport)...{
Integerkey
=newInteger(port);//hashtablekey
//LookuptheListenerobjectfortheportinthehashtable
finalListenerlistener=(Listener)services.get(key);
if(listener==null)return;
//Askthelistenertostop
listener.pleaseStop();
//Removeitfromthehashtable
services.remove(key);
//Andlogit.
log("Stoppingservice"+listener.service.getClass().getName()+
"onport"+port);
}


/***//**
*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)
throwsIOException
...{
super(group,"Listener:"+port);
listen_socket
=newServerSocket(port);
//giveitanon-zerotimeoutsoaccept()canbeinterrupted
listen_socket.setSoTimeout(5000);
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.
try...{
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)...{
try...{
//Thentelltheclientitisbeingrejected.
PrintWriterout=newPrintWriter(s.getOutputStream());
out.print(
"Connectionrefused;"+
"theserverisbusy;pleasetryagainlater. ");
out.flush();
//Andclosetheconnectiontotherejectedclient.
s.close();
//Andlogit,ofcourse
log("Connectionrefusedto"+
s.getInetAddress().getHostAddress()
+
":"+s.getPort()+":maxconnectionsreached.");
}
catch(IOExceptione)...{log(e);}
}

else...{//Otherwise,ifthelimithasnotbeenreached
//CreateaConnectionthreadtohandlethisconnection
Connectionc=newConnection(s,service);
//Addittothelistofcurrentconnections
connections.add(c);
//Logthisnewconnection
log("Connectedto"+s.getInetAddress().getHostAddress()+
":"+s.getPort()+"onport"+s.getLocalPort()+
"forservice"+service.getClass().getName());
//AndstarttheConnectionthreadtoprovidetheservice
c.start();
}

}


/***//**
*AConnectionthreadcallsthismethodjustbeforeitexits.Itremoves
*thespecifiedConnectionfromthesetofconnections.
*
*/

protectedsynchronizedvoidendConnection(Connectionc)...{
connections.remove(c);
log(
"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);
out.print(
"SERVICE"+listener.service.getClass().getName()
+"ONPORT"+port+" ");
}


//Displaythecurrentconnectionlimit
out.print("MAXCONNECTIONS:"+maxConnections+" ");

//Displayalistofallcurrentconnections
Iteratorconns=connections.iterator();
while(conns.hasNext())...{
Connectionc
=(Connection)conns.next();
out.print(
"CONNECTEDTO"+
c.client.getInetAddress().getHostAddress()
+
":"+c.client.getPort()+"ONPORT"+
c.client.getLocalPort()
+"FORSERVICE"+
c.service.getClass().getName()
+" ");
}

}


/***//**
*ThisclassisasubclassofThreadthathandlesanindividual
*connectionbetweenaclientandaServiceprovidedbythisserver.
*Becauseeachsuchconnectionhasathreadofitsown,eachServicecan
*havemultipleconnectionspendingatonce.Despitealltheother
*threadsinuse,thisisthekeyfeaturethatmakesthisa
*multi-threadedserverimplementation.
*
*/

publicclassConnectionextendsThread...{
Socketclient;
//Thesockettotalktotheclientthrough
Serviceservice;//Theservicebeingprovidedtothatclient

/***//**
*Thisconstructorjustsavessomestateandcallsthesuperclass
*constructortocreateathreadtohandletheconnection.Connection
*objectsarecreatedbyListenerthreads.Thesethreadsarepartof
*theserver'sThreadGroup,soallConnectionthreadsarepartofthat
*group,too.
*
*/

publicConnection(Socketclient,Serviceservice)...{
super("Server.Connection:"+
client.getInetAddress().getHostAddress()
+
":"+client.getPort());
this.client=client;
this.service=service;
}


/***//**
*ThisisthebodyofeachandeveryConnectionthread.
*Allitdoesispasstheclientinputandoutputstreamstothe
*serve()methodofthespecifiedServiceobject.Thatmethodis
*responsibleforreadingfromandwritingtothosestreamsto
*providetheactualservice.RecallthattheServiceobjecthas
*beenpassedfromtheServer.addService()methodtoaListener
*objecttotheaddConnection()methodtothisConnectionobject,and
*isnowfinallybeingusedtoprovidetheservice.Notethatjust
*beforethisthreadexitsitalwayscallstheendConnection()method
*toremoveitselffromthesetofconnections
*
*/

publicvoidrun()...{
try...{
InputStreamin
=client.getInputStream();
OutputStreamout
=client.getOutputStream();
service.serve(in,out);
}

catch(IOExceptione)...{log(e);}
finally...{endConnection(this);}
}

}


/***//**
*HereistheServiceinterfacethatwehaveseensomuchof.Itdefines
*onlyasinglemethodwhichisinvokedtoprovidetheservice.serve()
*willbepassedaninputstreamandanoutputstreamtotheclient.It
*shoulddowhateveritwantswiththem,andshouldclosethembefore
*returning.
*
*Allconnectionsthroughthesameporttothisserviceshareasingle
*Serviceobject.Thus,anystatelocaltoanindividualconnectionmust
*bestoredinlocalvariableswithintheserve()method.Statethat
*shouldbeglobaltoallconnectionsonthesameportshouldbestored
*ininstancevariablesoftheServiceclass.IfthesameServiceis
*runningonmorethanoneport,therewilltypicallybedifferent
*Serviceinstancesforeachport.Datathatshouldbeglobaltoall
*connectionsonanyportshouldbestoredinstaticvariables.
*
*Notethatimplementationsofthisinterfacemusthaveano-argument
*constructoriftheyaretobedynamicallyinstantiatedbythemain()
*methodoftheServerclass.
*
*/

publicinterfaceService...{
publicvoidserve(InputStreamin,OutputStreamout)throwsIOException;
}


/***//**
*Averysimpleservice.Itdisplaysthecurrenttimeontheserver
*totheclient,andclosestheconnection.
*
*/

publicstaticclassTimeimplementsService...{
publicvoidserve(InputStreami,OutputStreamo)throwsIOException...{
PrintWriterout
=newPrintWriter(o);
out.print(
newDate()+" ");
out.close();
i.close();
}

}


/***//**
*Thisisanotherexampleservice.Itreadslinesofinputfromthe
*client,andsendsthemback,reversed.Italsodisplaysawelcome
*messageandinstructions,andclosestheconnectionwhentheuser
*entersa'.'onalinebyitself.
*
*/

publicstaticclassReverseimplementsService...{
publicvoidserve(InputStreami,OutputStreamo)throwsIOException...{
BufferedReaderin
=newBufferedReader(newInputStreamReader(i));
PrintWriterout
=
newPrintWriter(newBufferedWriter(newOutputStreamWriter(o)));
out.print(
"Welcometothelinereversalserver. ");
out.print(
"Enterlines.Endwitha'.'onalinebyitself. ");
for(;;)...{
out.print(
">");
out.flush();
Stringline
=in.readLine();
if((line==null)||line.equals("."))break;
for(intj=line.length()-1;j>=0;j--)
out.print(line.charAt(j));
out.print(
" ");
}

out.close();
in.close();
}

}


/***//**
*ThisserviceisanHTTPmirror,justliketheHttpMirrorclass
*implementedearlierinthischapter.Itechosbacktheclient's
*HTTPrequest
*
*/

publicstaticclassHTTPMirrorimplementsService...{
publicvoidserve(InputStreami,OutputStreamo)throwsIOException...{
BufferedReaderin
=newBufferedReader(newInputStreamReader(i));
PrintWriterout
=newPrintWriter(o);
out.print(
"HTTP/1.0200 ");
out.print(
"Content-Type:text/plain ");
Stringline;
while((line=in.readLine())!=null)...{
if(line.length()==0)break;
out.print(line
+" ");
}

out.close();
in.close();
}

}


/***//**
*Thisservicedemonstrateshowtomaintainstateacrossconnectionsby
*savingitininstancevariablesandusingsynchronizedaccesstothose
*variables.Itmaintainsacountofhowmanyclientshaveconnectedand
*tellseachclientwhatnumberitis
*
*/

publicstaticclassUniqueIDimplementsService...{
publicintid=0;
publicsynchronizedintnextId()...{returnid++;}
publicvoidserve(InputStreami,OutputStreamo)throwsIOException...{
PrintWriterout
=newPrintWriter(o);
out.print(
"Youareclient#:"+nextId()+" ");
out.close();
i.close();
}

}


/***//**
*Thisisanon-trivialservice.Itimplementsacommand-basedprotocol
*thatgivespassword-protectedruntimecontrolovertheoperationofthe
*server.Seethemain()methodoftheServerclasstoseehowthis
*serviceisstarted.
*
*Therecognizedcommandsare:
*password:givepassword;authorizationisrequiredformostcommands
*add:dynamicallyaddanamedserviceonaspecifiedport
*remove:dynamicallyremovetheservicerunningonaspecifiedport
*max:changethecurrentmaximumconnectionlimit.
*status:displaycurrentservices,connections,andconnectionlimit
*help:displayahelpmessage
*quit:disconnect
*
*Thisservicedisplaysaprompt,andsendsallofitsoutputtotheuser
*incapitalletters.Onlyoneclientisallowedtoconnecttothis
*serviceatatime.
*
*/

publicstaticclassControlimplementsService...{
Serverserver;
//Theserverwecontrol
Stringpassword;//Thepasswordwerequire
booleanconnected=false;//Whetheraclientisalreadyconnected

/***//**
*CreateanewControlservice.ItwillcontrolthespecifiedServer
*object,andwillrequirethespecifiedpasswordforauthorization
*NotethatthisServicedoesnothaveanoargumentconstructor,
*whichmeansthatitcannotbedynamicallyinstantiatedandaddedas
*theother,genericservicesabovecanbe.
*
*/

publicControl(Serverserver,Stringpassword)...{
this.server=server;
this.password=password;
}


/***//**
*Thisistheservemethodthatprovidestheservice.Itreadsa
*linetheclient,andusesjava.util.StringTokenizertoparseit
*intocommandsandarguments.Itdoesvariousthingsdependingon
*thecommand.
*
*/

publicvoidserve(InputStreami,OutputStreamo)throwsIOException...{
//Setupthestreams
BufferedReaderin=newBufferedReader(newInputStreamReader(i));
PrintWriterout
=newPrintWriter(o);
Stringline;
//Forreadingclientinputlines
//Hastheuserhasgiventhepasswordyet?
booleanauthorized=false;

//Ifthereisalreadyaclientconnectedtothisservice,display
//amessagetothisclientandclosetheconnection.Weusea
//synchronizedblocktopreventaracecondition.
synchronized(this)...{
if(connected)...{
out.print(
"ONLYONECONTROLCONNECTIONALLOWED. ");
out.close();
return;
}

elseconnected=true;
}


//Thisisthemainloop:readacommand,parseit,andhandleit
for(;;)...{//infiniteloop
out.print(">");//Displayaprompt
out.flush();//Makeitappearrightaway
line=in.readLine();//Gettheuser'sinput
if(line==null)break;//QuitifwegetEOF.
try...{
//UseaStringTokenizertoparsetheuser'scommand
StringTokenizert=newStringTokenizer(line);
if(!t.hasMoreTokens())continue;//ifinputwasempty
//Getfirstwordoftheinputandconverttolowercase
Stringcommand=t.nextToken().toLowerCase();
//Nowcomparetoeachofthepossiblecommands,doingthe
//appropriatethingforeachcommand
if(command.equals("password"))...{//Passwordcommand
Stringp=t.nextToken();//Getthenextword
if(p.equals(this.password))...{//Isitthepassword?
out.print("OK ");//Sayso
authorized=true;//Grantauthorization
}

elseout.print("INVALIDPASSWORD ");
}

elseif(command.equals("add"))...{//AddServicecommand
//Checkwhetherpasswordhasbeengiven
if(!authorized)out.print("PASSWORDREQUIRED ");
else...{
//Getthenameoftheserviceandtryto
//dynamicallyloadandinstantiateit.
//Exceptionswillbehandledbelow
StringserviceName=t.nextToken();
ClassserviceClass
=Class.forName(serviceName);
Serviceservice;
try...{
service
=(Service)serviceClass.newInstance();
}

catch(NoSuchMethodErrore)...{
thrownewIllegalArgumentException(
"Servicemusthavea"+
"no-argumentconstructor");
}

intport=Integer.parseInt(t.nextToken());
//Ifnoexceptionsoccurred,addtheservice
server.addService(service,port);
out.print(
"SERVICEADDED ");//acknowledge
}

}

elseif(command.equals("remove"))...{//Removeservice
if(!authorized)out.print("PASSWORDREQUIRED ");
else...{
intport=Integer.parseInt(t.nextToken());
server.removeService(port);
//removetheservice
out.print("SERVICEREMOVED ");//acknowledge
}

}

elseif(command.equals("max"))...{//Setconnectionlimit
if(!authorized)out.print("PASSWORDREQUIRED ");
else...{
intmax=Integer.parseInt(t.nextToken());
server.setMaxConnections(max);
out.print(
"MAXCONNECTIONSCHANGED ");
}

}

elseif(command.equals("status"))...{//StatusDisplay
if(!authorized)out.print("PASSWORDREQUIRED ");
elseserver.displayStatus(out);
}

elseif(command.equals("help"))...{//Helpcommand
//Displaycommandsyntax.Passwordnotrequired
out.print("COMMANDS: "+
" password<password> "+
" add<service><port> "+
" remove<port> "+
" max<max-connections> "+
" status "+
" help "+
" quit ");
}

elseif(command.equals("quit"))break;//Quitcommand.
elseout.print("UNRECOGNIZEDCOMMAND ");//Error
}

catch(Exceptione)...{
//Ifanexceptionoccurredduringthecommand,printan
//errormessage,thenoutputdetailsoftheexception.
out.print("ERRORWHILEPARSINGOREXECUTINGCOMMAND: "+
e
+" ");
}

}

//Finally,whentheloopcommandloopends,closethestreams
//andsetourconnectedflagtofalsesothatotherclientscan
//nowconnect.
connected=false;
out.close();
in.close();
}

}

}

分享到:
评论

相关推荐

    Java2平台安全技术-结构,API设计和实现

    安全相关的异常如`SecurityException`会在不安全的操作尝试时抛出,这是Java安全机制的重要反馈机制。 5. **签名与证书** 对于可信任的代码,Java支持使用数字签名和证书进行验证。签名能确保代码未被篡改,而...

    JAVA 2平台安全技术-结构,API设计和实现

    本主题将深入探讨Java安全模型的结构、API设计以及其实现方式。 一、Java安全模型的结构 Java的安全模型基于三个主要组件:类加载器、安全策略和权限管理。类加载器负责加载类到JVM中,通过不同的类加载器可以实现...

    java的反射机制原理

    本文将详细介绍 Java 反射机制的基本原理以及其实现方式。 #### 二、反射机制的核心概念 Java 反射机制主要依赖于以下几个核心概念: 1. **`Class` 类**:表示一个类的对象,包含了关于类的所有信息,包括类名、...

    Java卡应用开发其实并不难.doc

    这些版本的规范定义了如何在Java卡上创建、管理和执行应用程序,包括卡片的安全机制、文件系统以及与外界的通信协议。 开发环境是Java卡应用开发的关键部分。Eclipse作为一个开源的Java开发环境,因其便捷性和灵活...

    Java的线程和Java AppletJava的线程和Java AppletJava的线程和Java Applet

    2. **安全性**:Java Applet运行在Java安全沙箱内,限制了对本地系统资源的访问,以保护用户的系统安全。 3. **网络通信**:Applet可以与服务器进行通信,获取数据或更新自身。 4. **生命周期**:Applet有自己的...

    Java理论与实践:描绘线程安全性

    例如,`java.lang.String`就是不可变的,多个线程可以安全地共享同一个字符串实例。 其次,线程安全(Thread-Safe)的类是指无论在何种并发环境下,其实例都能保证正确的行为。这些类内部实现了必要的同步机制,...

    娄不夜-面向对象的程序设计与java全书源代码与课后题源代码

    在Java中,类是创建对象的模板,每个类都定义了其实例的行为和属性。类的实例化过程就是创建对象,而对象之间可以通过继承、封装和多态等机制实现复杂的数据结构和功能。 1. **类与对象**:类是对象的蓝图,它定义...

    Java学习利器-JAVA解惑

    6. **集合框架**:Java集合框架是开发者经常打交道的一部分,包括List、Set、Map等接口以及其实现类的使用和优化。"JAVA解惑"可能针对这些内容提供实践指导。 7. **IO与NIO**:Java的输入输出系统和非阻塞I/O模型...

    java 开发实战经典

    《Java开发实战经典》课程是为那些希望深入理解Java编程语言并掌握其实战技能的人们设计的。这个课程从基础开始,逐步引导学习者进入Java的世界。"Java学习概述笔记"这部分内容,作为课程的开篇,旨在为初学者提供一...

    毕业论文的英文翻译 计算机安全方面

    随着时间的推移,Java安全模型逐渐增强,包括类加载器机制、访问控制、数字签名和证书等,这些都旨在提升移动代码的信任度。 Java提供了多种安全API和工具,例如Java Cryptography Extension (JCE)用于加密,Java ...

    java面试题集(网上全部题目都在这里不用去别处找了!)

    4. **集合框架**:Java集合框架包括List、Set、Map等接口以及其实现类,如ArrayList、LinkedList、HashSet、HashMap等。面试时可能会问到它们的特性、增删改查操作、遍历方式、性能比较等。 5. **多线程**:Java...

    关于线程(java)两天的课件

    Java提供了多种机制,如synchronized关键字、volatile变量、Lock接口(如ReentrantLock)以及信号量Semaphore。synchronized提供内置锁,保证同一时间只有一个线程访问临界区;volatile保证了变量在多线程环境中的...

    java oracle并发官方教程

    总结来说,Java的并发编程涉及进程和线程的概念、线程的创建和管理、线程同步机制、活跃度问题的解决方法、不可变对象的使用以及高级并发工具的应用等多个方面。掌握这些知识点对于编写高性能和高可用性的Java程序至...

    java学习重点

    JAVA学习要点 一、关于Java ...多态性就是“一种接口,多种方法”,可以为一组相关的动作设计一个通用的接口,其实类的函数的重载就是一种多态的体现; 4 引入抽象编程的思想; 类的封装就是一种抽象思想

    Java源码,JAVA代码

    4. **Java集合框架**:List、Set、Map接口以及其实现类,如ArrayList、LinkedList、HashSet、HashMap等。 5. **IO流**:了解输入/输出流的分类,掌握File类、BufferedReader和Writer等常用类的用法。 6. **多线程*...

Global site tag (gtag.js) - Google Analytics