Java journey -- Communication and java journey --

Source: Internet
Author: User

Java journey -- Communication and java journey --


Overview


Communication comes from the network. The network is divided into seven layers: physical layer, data link layer, network layer, transmission layer, Session Layer, presentation layer, and application layer. Communication is based on the protocol, there are many common protocols, such as network layer protocol IP, transport layer protocol TCP/UDP, and application layer protocol HTTP/SOAP/REST.

We will also often hear about sockets, and TCP/IP should also provide interfaces for programmers to do network development. This is the Socket programming interface. There is a metaphor: HTTP is a car that provides a specific form of encapsulation or display data; Socket is an engine that provides network communication capabilities.

Communication is supported in any language. Today we use Java to demonstrate several commonly used communication technologies in Java, including: socket, Http, REST, Dubbo, Thrift, and FTP.


Socket


SocketServer. java

Import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; import java.net. serverSocket; import java.net. socket; public class SocketServer {public static void main (String [] args) {SocketServer ss = new SocketServer (); // set the server port number ServerSocket s = null; try {s = new serversockets (100 99); System. out. println ("ServerSocket Start:" + s); while (true) {Socket socket = s. accept (); // This is the blocked System. out. println ("Server_Accept:" + socket); SocketServer. handleSocket vsm = ss. new HandleSocket (socket); new Thread (vsm ). start () ;}} catch (IOException e) {e. printStackTrace ();} finally {try {s. close ();} catch (IOException e) {}} class HandleSocket implements Runnable {private Socket socket; public Handle Socket (Socket socket) {this. socket = socket ;}@ Overridepublic void run () {BufferedReader br = null; PrintWriter pw = null; try {// used to receive requests sent from the client br = new BufferedReader (new InputStreamReader (socket. getInputStream (); // It is used to send returned information. You do not need to describe so many io streams to send data when using buffered streams. flush () method pw = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket. getOutputStream (), true); String str = br. readLine (); if (str! = Null) {pw. println ("OK _" + Thread. currentThread (). getName (); pw. flush (); System. out. println ("Command:" + str) ;}} catch (Exception e) {e. printStackTrace ();} finally {System. out. println ("Server_Close:" + socket); try {br. close (); pw. close (); socket. close () ;}catch (Exception e2 ){}}}}}

SocketClient. java

Import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; import java.net. socket; public class SocketClient {public static void main (String [] args) throws InterruptedException {for (int I = 0; I <10; I ++) {call ("Hello" + I) ;}} public static void call (String command) {Socket socket = null; BufferedReader br = null; PrintWriter pw = null; try {// The client socket specifies the server address and port number socket = new Socket ("127.0.0.1", 10099); System. out. println ("Client_Open" + socket + "Command:" + command); // same as the server principle br = new BufferedReader (new InputStreamReader (socket. getInputStream (); pw = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket. getOutputStream (); pw. println (command); pw. flush (); String str = br. readLine (); System. out. println ("Client_Receive:" + str);} catch (Exception e) {e. printStackTrace ();} finally {try {System. out. println ("Client_Close:" + socket); br. close (); pw. close (); socket. close ();} catch (Exception e) {e. printStackTrace ();}}}}

Http


HttpConnection Demonstration: HttpConnectionTest. java

Import java. io. bufferedReader; import java. io. inputStreamReader; import java. io. outputStream; import java. io. outputStreamWriter; import java.net. httpURLConnection; import java.net. URL; public class HttpConnectionTest {public static void main (String [] args) throws Exception {System. out. println ("begin send"); String inputParam = "<? Xml version = \ "1.0 \" encoding = \ "UTF-8 \"?> <Content> Test </content> </page> "; URL = null; HttpURLConnection httpConn = null; OutputStream output = null; OutputStreamWriter outr = null; // url = new URL ("http: // 127.0.0.1: 8888/iotest/ReadServlet"); url = new URL ("http://www.baidu.com"); httpConn = (HttpURLConnection) url. openConnection (); httpConn. setConnectTimeout (30000); httpConn. setReadTimeout (30000); HttpURLConnection. setFollowRedirects (true); ht TpConn. setDoOutput (true); httpConn. setRequestMethod ("POST"); httpConn. setRequestProperty ("Content-Type", "text/xml"); httpConn. connect (); output = httpConn. getOutputStream (); outr = new OutputStreamWriter (output); // write the request parameter outr. write (inputParam. toString (). toCharArray (), 0, inputParam. toString (). length (); outr. flush (); outr. close (); System. out. println ("send OK"); int code = httpConn. getResponseCode (); System. Out. println ("code" + code); System. out. println (httpConn. getResponseMessage (); // read the response String sCurrentLine = ""; String sTotalString = ""; if (code = 200) {java. io. inputStream is = httpConn. getInputStream (); BufferedReader reader = new BufferedReader (new InputStreamReader (is); while (sCurrentLine = reader. readLine ())! = Null) if (sCurrentLine. length ()> 0) sTotalString = sTotalString + sCurrentLine. trim ();} else {sTotalString = "remote server connection failed, error code:" + code;} System. out. println ("response:" + sTotalString );}}


Dubbo


... To be continued


Thrift


... To be continued


Rest

... To be continued


FTP


... To be continued

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.