> Connecting to a server via sockets
Socket refers to socket
> read the homepage of any website
---------
/** * @author Lean @date: 2014-10-9 */public class Socketsample {public static void main (S Tring[] args) {BufferedWriter writer=null; Socket Socket=null;try {while (true) {try {Thread.Sleep],} catch (Interruptedexception e) {e.printstacktrace ();} Socket=new Socket ("localhost", 8080), OutputStream outputstream=socket.getoutputstream (); Outputstream.write ("GET/ Http/1.0\n\n ". GetBytes ()); BufferedReader reader=new BufferedReader (New InputStreamReader (Socket.getinputstream ())); Writer=new BufferedWriter (New OutputStreamWriter (New FileOutputStream ("c:/users/administrator/desktop/theadsample.html")); String Appendstr=null;while ((appendstr=reader.readline ()) = null) {//system.out.println (APPENDSTR); Writer.write ( APPENDSTR);} Writer.close (); Reader.close ();}} catch (Unknownhostexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} Finally{if (socket!=null) {try {socket.close ();} catch (IOException e) {e.printstacktrace ();}}}}
---------
> download any page via URL
---------
/** * @author Lean @date: 2014-10-9 */public class Urlsample {public static void main (string[] args) {try {URL url= New URL ("HTTP", "www.baidu.com", "+"),//url url=new url ("http://www.baidu.com"); HttpURLConnection connection= (httpurlconnection) url.openconnection (); Connection.connect (); InputStream is= Connection.getinputstream (); byte[] Buff=new byte[1024];int length=0;while ((Length=is.read (Buff))!=-1) { System.out.println (new String (Buff));}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}}
---------
> Detect incoming Cookie information on the website
---------
/** * @author Lean @date: 2014-10-9 */public class Httpcookiesample {/** * @param args */public static void main (string[ ] args) {Cookiemanager manager=new cookiemanager (); Manager.setcookiepolicy (new Customerpolicy ()); Cookiehandler.setdefault (manager); try {URL url=new url ("http://www.baidu.com"); URLConnection conn=url.openconnection (); Object content=conn.getcontent (); List---------
> Writing server programs that serve multiple clients at the same time
---------
/** * @author Lean @date: 2014-10-9 */public class Serversocketsample {private static ServerSocket server=null; public static void Main (string[] args) {try {server=new serversocket (8080); Executorservice Pool=executors.newfixedthreadpool (3); while (true) {Socket socketobject= server.accept ();p Ool.submit (New Customrunnable (Socketobject));}} catch (IOException e) {e.printstacktrace ();}} Static class Customrunnable implements runnable{byte[] buff=new byte[512];p rivate Socket socketobject;public Customrunnable (Socket socketobject) {this.socketobject=socketobject;} @Overridepublic void Run () {try {System.out.println ("Thread id>>" +thread.currentthread (). GetId ()); InputStream Stream=socketobject.getinputstream (); Stream.read (buff); OutputStream os=socketobject.getoutputstream (); Os.write ( Buff); Socketobject.close ();} catch (IOException e) {e.printstacktrace ();}}}}
---------
> writing the actual file Storage Server program
---------
Storgeserversample
/** * @author Lean @date: 2014-10-10 */public class Storgeserversample {public static void main (string[] args) {Serverso Cket Socket=null; Executorservice Service=executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors ()); try {socket=new ServerSocket (8080); try {while (true) {Socket socketobject=socket.accept (); Service.submit (New Requestrunnable ( Socketobject));}} Finally{socket.close ();}} catch (IOException e) {e.printstacktrace ();}} Static class Requestrunnable implements Runnable{private socket Requestsocket;public requestrunnable (socket Socketobject) {requestsocket=socketobject;} @Overridepublic void Run () {try {datainputstream datais=new DataInputStream (Requestsocket.getinputstream ());D Ataoutputstream dataos=new DataOutputStream (Requestsocket.getoutputstream ()); int Cmd=datais.readint (); String message=cmd==0? " Put ":" Get "; String Filename=datais.readutf (); message+=filename+ "REQUEST"; filename= "C:/Documents and settings/administrator/Desktop /server.txt "; if (cmd==0) {UploadFile (dAtais,filename);} else {downfile (dataos,filename);}} catch (IOException e) {e.printstacktrace ();}} private void UploadFile (DataInputStream datais, String fileName) {try {bufferedwriter writer=new bufferedwriter (new FileWriter (FileName)); String Tempstr;while (! ( Tempstr=datais.readutf ()). Equals ("-1")) {writer.write (TEMPSTR); Writer.newline ();} Writer.close ();d atais.close ();} catch (IOException e) {e.printstacktrace ();}} private void Downfile (DataOutputStream Dataos, String fileName) {try {BufferedReader reader=new BufferedReader (new FileReader (FileName)); String Tempstr=null;while ((Tempstr=reader.readline ())!=null) {Dataos.writeutf (TEMPSTR);} Dataos.writeutf ("1");d ataos.close (); Reader.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}}}
---------Storgeclientsample
public class Storgeclientsample {public static void main (string[] args) {int Cmd=1;try {socket requestscoket=new socket (); Requestscoket.connect (New inetsocketaddress ("localhost", 8080)); if (cmd==0) {String filename= "c:/documents and settings/administrator/Desktop/test.txt "; BufferedReader reader=new BufferedReader (New FileReader (fileName));D Ataoutputstream dataos=new DataOutputStream ( Requestscoket.getoutputstream ());d ataos.writeint (cmd);d ataos.writeutf (fileName); String Tempstr;while ((Tempstr=reader.readline ())!=null) {System.out.println (TEMPSTR);d Ataos.writeutf (TEMPSTR);} Dataos.writeutf ("1");d ataos.close (); Reader.close ();} else {String filename= "c:/documents and settings/administrator/desktop/down.txt"; BufferedWriter writer=new BufferedWriter (New FileWriter (fileName));D Ataoutputstream dataos=new DataOutputStream ( Requestscoket.getoutputstream ());d ataos.writeint (cmd);d ataos.writeutf (fileName);D Atainputstream datais=new DataInputStream (Requestscoket.getinputstream ()); String Tempstr;while (! ( Tempstr=Datais.readutf ()). Equalsignorecase ("1")) {System.out.println (TEMPSTR); Writer.write (TEMPSTR); Writer.newline ();} Datais.close (); Writer.close ();}} catch (IOException e) {e.printstacktrace ();}}}
---------> Creating multi-Wave servers and clients
---------
Stocktradesserver
/** * @author Lean @date: 2014-10-11 */public class Stocktradesserver {public static void main (string[] args) {Thread St Ocksthread=new Thread (New Stocktradegenerator ()); Stocksthread.setdaemon (true); Stocksthread.start (); try { Thread.Sleep (30000);} catch (Interruptedexception e) {}}static class Stocktradegenerator implements Runnable{private Datagramsocket Broadcastsocket;private string[] stocksymbols ={"IBM", "SNE", "XRX", "MHP", "NOK"};p ublic Stocktradegenerator () {try { Broadcastsocket=new Datagramsocket (4445);} catch (SocketException e) {System.out.println ("Error create socket!");}} @Overridepublic void Run () {byte[] buff=new byte[126];try {while (true) {int index= (int) (Math.random ()); float Trade=ge Neratorrandomtrade (index); String Tempstr=string.format ("%s%[email protected]%s", Stocksymbols[index],trade,now ()); buff= Tempstr.getbytes (); InetAddress groupinetaddresses;groupinetaddresses = Inetaddress.getlocalhost ();D Atagrampacket Datagrampacket=new Datagrampacket (Buff,buff.length,groupinetaddresses,4446); Broadcastsocket.send (Datagrampacket); Thread.Sleep (500);}} catch (Unknownhostexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} catch ( Interruptedexception e) {e.printstacktrace ();} Finally{broadcastsocket.close ();}}} public static float Generatorrandomtrade (int index) {float trade= (float) math.random (), switch (index) {case 0:trade+=118 ; break;case 1:trade+=29;break;case 2:trade+=8;break;case 3:trade+=26;break;case 4:trade+=14;break;default:break;} return trade;} public static Object Now () {SimpleDateFormat df=new SimpleDateFormat ("HH:mm:ss");D ate date=new Date (); return Df.format ( date);}}
---------Stocktradeclient
/** * @author Lean @date: 2014-10-11 */public class Stocktradeclient {public static void main (string[] args) throw s IOException {multicastsocket multicastsocket=new multicastsocket (4446); InetAddress Address=InetAddress.getByName ( "232.0.1.1"); Multicastsocket.joingroup (address); for (int i = 0; i < i++) {byte[] buff=new byte[256];D atagrampacket Datagrampacket=new Datagrampacket (buff,buff.length); multicastsocket.receive (Datagrampacket); System.out.println (New String (Datagrampacket.getdata (), 0,datagrampacket.getlength ()));} Multicastsocket.leavegroup (address); Multicastsocket.close ();}}
---------
Java Advanced-Network programming