JAVA advanced-network programming, 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<HttpCookie> 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();}}
---------
Java Network Programming Basics
Java basics must be met.
Network Programming does not have much to do with it. It requires a higher level of thread and concurrency.
For some simple applications, if you have a good foundation, read the books for two weeks and contact us. JAVA provides a set of APIS for TCP and UDP protocols, and I/O is required.
If the research is deep, it will be complicated. The implementation of various protocols and underlying system operations are very complicated. I also don't quite understand them. Come on step by step.
JAVA programming this book has knowledge about network programming, as well as exercises and examples.
How to Learn java Network Programming
Java is oriented to j2ee.
J2ee is more than just socket programming, including the core technology in section 13.
Core APIs and components of J2EE
The J2EE platform consists of a complete set of Services, application interfaces (APIs), and Protocols. It provides Function Support for developing Web-based multi-layer applications, the following is a brief description of the 13 technical specifications in J2EE (limited by space ):
1. JDBC (Java Database Connectivity ):
JDBC APIs provide a unified way to access different databases. Like ODBC, JDBC shields developers from some details. In addition, JDCB's access to the database is also platform-independent.
2. JNDI (Java Name and Directory Interface ):
The jndi api is used to run the name and directory services. It provides a consistent model to access and operate enterprise-level resources such as DNS and LDAP, local file systems, or objects on application servers.
3. EJB (Enterprise JavaBean ):
One of the reasons why J2EE technology has won widespread media attention is EJB. They provide a framework for developing and implementing distributed business logic, significantly simplifying the development of scalable and highly complex enterprise-level applications. The EJB specification defines when and how the EJB component interacts with their containers. Containers are responsible for providing public services, such as directory services, transaction management, security, resource buffer pools, and fault tolerance. However, it is worth noting that EJB is not the only way to implement J2EE. Due to the openness of J2EE, some vendors can achieve the same purpose in parallel with EJB.
4. RMI (Remote Method Invoke ):
As its name indicates, the RMI protocol calls methods on remote objects. It uses serialization to transmit data on the client and server. RMI is a more underlying protocol used by EJB.
5. Java IDL/CORBA:
With the support of Java IDL, developers can integrate Java and CORBA. They can create Java objects and expand them in corba orb, or they can also create Java classes and serve as the customers of the CORBA objects expanded with other ORB. The latter method provides another way through which Java can be used to integrate your new applications with old systems.
6. JSP (Java Server Pages ):
A JSP page consists of HTML code and Java code embedded in it. The server processes the Java code after the page is requested by the client, and then returns the generated HTML page to the browser of the client.
7. Java Servlet:
Servlet is a small Java program that extends the functions of Web servers. As a server-side application, it is executed when requested, which is similar to CGI Perl script. Most of the functions provided by Servlet are similar to those provided by JSP, but the implementation methods are different. JSP usually embeds a small amount of Java code in most HTML code, while servlets is all written in Java and generates HTML.
8. XML (Extensible Markup Language ):
XML is a language that can be used to define other Markup languages. It is used to share data in different business processes.
The development of XML and Java are mutually independent. However, the same objective of XML and Java is platform independence. By combining Java and XML, you can get a perfect platform-independent solution.
9. JMS (Java Message Service ):
MS is an application interface (API) used to communicate with message-oriented middleware ). It supports point-to-point domains and supports Publishing.