JAVA advanced-Network Programming

Source: Internet
Author: User

JAVA advanced-Network Programming
> Connect to the server through a socket
Socket refers to Socket


> Read the homepage of any website
---------

/** * @author Lean  @date:2014-10-9   */public class SocketSample {public static void main(String[] args) {BufferedWriter writer=null;Socket socket=null;try {while (true) {try {Thread.sleep(1000);} 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 Webpage Through 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",80,"");//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();}}}
---------
> Checks the cookie information sent from 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
 
   cookies=manager.getCookieStore().getCookies();for (HttpCookie httpCookie : cookies) {System.out.println(httpCookie.getName()+"  "+httpCookie.getValue()+"    "+httpCookie.getDomain());printCookieLiveAge(httpCookie);System.out.println("Cookie secured:"+httpCookie.getSecure());System.out.println("...........");}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}private static void printCookieLiveAge(HttpCookie httpCookie) {long age=httpCookie.getMaxAge();SimpleDateFormat df=new SimpleDateFormat("HH:mm:ss");System.out.println(age!=-1?"Cookie will expire when close ":"Cookie age is:"+df.format(age));}static class CustomerPolicy implements CookiePolicy{@Overridepublic boolean shouldAccept(URI uri, HttpCookie cookie) {return true;}}}
 
---------
> Compile a server program that serves 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();pool.submit(new CustomRunnable(socketObject));}} catch (IOException e) {e.printStackTrace();}}static class CustomRunnable implements Runnable{byte[] buff=new byte[512];private 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();}}}}
---------
> Compile the actual file storage server program
---------

StorgeServerSample

/*** @ Author Lean @ date: 2014-10-10 */public class StorgeServerSample {public static void main (String [] args) {ServerSocket 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 (); DataOutputStream dataOs = new DataOutputStream (requestSocket. getOutputStream (); int cmd = dataIs. re AdInt (); 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 (); dataIs. 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"); dataOs. 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); DataOutputStream dataOs = new DataOutputStream (requestScoket. getOutp UtStream (); dataOs. writeInt (cmd); dataOs. writeUTF (fileName); String tempStr; while (tempStr = reader. readLine ())! = Null) {System. out. println (tempStr); dataOs. writeUTF (tempStr);} dataOs. writeUTF ("-1"); dataOs. close (); reader. close ();} else {String fileName = "C:/Documents and Settings/Administrator/desktop/Down.txt"; BufferedWriter writer = new BufferedWriter (new FileWriter (fileName )); dataOutputStream dataOs = new DataOutputStream (requestScoket. getOutputStream (); dataOs. writeInt (cmd); dataOs. writeUTF (fileName); DataInputStream da TaIs = 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 ();}}}
---------

> Create multiple radio wave servers and clients

---------

StockTradesServer

/** * @author Lean  @date:2014-10-11   */public class StockTradesServer {public static void main(String[] args) {Thread stockSThread=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"};public 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()*5);float trade=generatorRandomTrade(index);String tempStr=String.format("%s %.2f@ %s",stockSymbols[index],trade,now());buff=tempStr.getBytes();InetAddress groupInetAddresses;groupInetAddresses = InetAddress.getLocalHost();DatagramPacket 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");Date date=new Date();return df.format(date);}}
---------

StockTradeClient

/** * @author Lean  @date:2014-10-11   */public class StockTradeClient {public static void main(String[] args) throws IOException {MulticastSocket multicastSocket=new MulticastSocket(4446);InetAddress address=InetAddress.getByName("232.0.1.1");multicastSocket.joinGroup(address);for (int i = 0; i < 10; i++) {byte[] buff=new byte[256];DatagramPacket datagramPacket=new DatagramPacket(buff,buff.length);multicastSocket.receive(datagramPacket);System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));}multicastSocket.leaveGroup(address);multicastSocket.close();}}
---------


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.