JAVA 24 network communication

Source: Internet
Author: User
Tags closing tag ftp protocol

Network Reference Model:--|| OSI Reference Model--| | TCP/IP Reference Model Application layer: HTTP protocol, FTP protocol Transport layer: TCP,UDP internetwork: IP TCP and UDP:UDP:1, for the non-connected, need to encapsulate data in the packet 2, each packet size limit within 64k 3, no connection, is unreliable protocol 4, because no connection, fast tcp:1, need to establish a connection, the formation of data transmission Channel 2, in the connection of large data transmission 3, through three handshake to complete the connection, is a reliable protocol A: already you in? Already: I am in a: I know you are in the 4, you must establish a connection, the efficiency is slightly lower Important Object Introduction  InetAddress method Description: 1,static inetaddress getlocalhost ()//Get Local host ip2,static inetaddress Getbyname (String ip/name) Socketsocket is a mechanism for network services to communicate on both ends of the socket network communication is actually the communication between the sockets between two sockets through IO transmission UDP Socket Transfer Service object:Datagramsocket (port/optional Accept port) 1,void send (Datagrampacket p) 2,void receive (Datagrampacket p) Datagrampacket: Construction method: Datagrampacket (byte[] buf,int length) datagrampacket (byte[] buf,int length,inetaddress ad,int Port) Soceket service object for TCPTCP sub-client and server. Case One   TCP End Mode 1, the client sends the end tag, single if the sent data contains the tag is not good//not recommended 2, timestamp method, first send a time stamp, in the sending time stamp, when the server read to the second time stamp stop TCP communication //not recommended 3,shutdowninput (), shutdowmoutput ()//off input/output stream, equivalent to join end tag/* Client, by looking at the socket object, discovers that when the object is established, it can connect to the specified host. Because TCP is connection-oriented. Therefore, in the establishment of the socket service, there must be a server exists, and the connection is successful. After the pathway is formed, the data is transmitted in the channel.    requirements: Send the server to a text data.   Steps: 1, create a socket service. and specify the host and port to connect to.  */import java.io.*;import java.net.*;class  tcpclient{ public static void Main (string[] args) throws exception { //Create the client socket service. Specify the destination host and port   SOCKET s = new socket ("192.168.1.254", 10003);  //In order to send data, you should get the output stream in the socket stream.   OutputStream out = S.getoutputstream ();   out.write ("tcp ge Men lai le". GetBytes ());    S.close (); }}    requirements: Define the endpoint to receive data and print it on the console. Server: 1, set up the socket service side. ServerSocket ();  and listens on a port. 2. Gets the client object that is connected.   through Serversokcet's Accept method. No connection will wait, so this method is blocking. 3, if the client sends the data, then the server will use the corresponding client object and fetch the read stream to the client object to read the data sent.   and print on the console.  4, close the server. (optional)   */class  tcpserver{ public static void Main (string[] args) throws exception { // Set up a service-side socket service. And listen for a port.   ServerSocket SS = new ServerSocket (10003);  //ThroughThe Accept method gets the client object that is connected.   while (true)   {  Socket s = ss.accept ();   String IP = s.getinetaddress (). gethostaddress (); nbsp System.out.println (ip+ "... connected");  //Get the data sent by the client, then use the read stream of the client object to read the data.   InputStream in = S.getinputstream ();   byte[] buf = new byte[1024];  int len = In.read (BUF);  &n Bsp System.out.println (New String (Buf,0,len));   s.close ();//Close client . } //ss.close ();  }}      Exercise Two /* Requirements: Establish a text conversion server. The client sends text to the server, and the service order converts the text to uppercase in return to the client. and the customer degree can continue to do text conversion. When the client enters over, the conversion ends. Analysis: Client: since it is the operation of the data on the device, then you can use IO technology, and according to the operational rules of IO thinking. Source: Keyboard entry. Purpose: Network device, network output stream. It also operates on text data. You can select a character stream. Steps 1, set up the service. 2, get keyboard entry. 3. Send the data to the server. 4, then go back to the server to return the uppercase data. 5, end, close resources. are text data and can be used The character stream, while increasing efficiency and adding buffering. Service side: Source: Socket read stream. Purpose: The socket output stream. It's all text and decorations.     The problem arises from this example. phenomenon: The client and the service side are in inexplicable wait. for what? because both the client and the server have a blocking method. These methods do not read to the closing tag. Then just keep waiting . and lead to both ends, are waiting.     the client and server-side output streams in the following example can be used PrintWriter out = new PrintWriter (S.getinputstream ()) instead   ClientImport Java.io.*;import java.net.*; public class Test {public static void main (string[] args) throws Exception {socket s = new socket ("localhost", 9999); BufferedWriter bufout = new BufferedWriter (New OutputStreamWriter (S.getoutputstream ())); BufferedReader Bufin = new BufferedReader (New InputStreamReader (S.getinputstream ())); BufferedReader br= New BufferedReader (New InputStreamReader (system.in));   while (true) {String line =br.readline ();  Bufout.write (line);  Bufout.newline ();   Bufout.flush ();  if ("Over". Equals (line) is break;  String data =bufin.readline ();    SOP ("server:" +data);} S.close ();   } public static void sop (Object o) {System.out.println (o); }} Service Side  Import Java.io.*;import java.net.*;p ublic class Zhangxu {public static void main (string[] args) throws Exception {Serv  Ersocket s = new ServerSocket (9999);  Socket ss = S.accept ();  SOP (Ss.getinetaddress (). gethostaddress ());  BufferedWriter bufout = new BufferedWriter (New OutputStreamWriter (Ss.getoutputstream ()));  BufferedReader Bufin = new BufferedReader (New InputStreamReader (Ss.getinputstream ()));  while (true) {String line =bufin.readline ();//Because the client did not send a return, so it has not been read, the client should be printed with a newline sop (lines);  Bufout.write (Line.touppercase ());  Bufout.newline ();  Bufout.flush ();   }} public static void sop (Object o) {System.out.println (o); }} example of UDP communication/*requirements: Send a piece of text via UDP transmission1, set up UDP socket service2, improve the data, the data shroud into the packet3. Send packet via socket service send function4, close the resourcerequirements: Receive the data sent over1, a UDP socket service is established, typically a receive port is defined. 2, set up the data packet to hold the data, store the received byte data, because the packet object has the method to extract the information. 3, listen through the Receive method and accept the data stored in the defined packet. 4, the different data is taken out by the special function of the packet object. 5, close the resource */ Send Side import java.io.IOException;import java.net.*;Public class Test {Public static void Main (string[] args) throws IOException {SOP (111);datagramsocket ds = new Datagramsocket ();byte [] data = "udp haha". getBytes ();Datagrampacket dp = new Datagrampacket (Data,data.length,inetaddress.getlocalhost (), 8888);Ds.send (DP);ds.close ();   }Public static void sop (Object o) {System.out.println (o);  }}Receiving Endimport java.net.*;Public class Zhangxu {Public static void Main (string[] args) throws Exception {SOP ("Listen ...");datagramsocket ds= New Datagramsocket (8888);//Set up a listening portbyte [] buf = new byte[1024];Datagrampacket dp = new Datagrampacket (buf,buf.length);Ds.receive (DP); String IP =dp.getaddress (). gethostaddress ();String data = new String (Dp.getdata (), 0,dp.getlength ());int port = Dp.getport (); SOP (ip+ "--" +data+ "--" +port ");ds.close (); } Public static void sop (Object o) {System.out.println (o);  }} /* requirements: TCP uploads images.       */ /* client. 1, service endpoint. 2, read the client's existing picture data. 3, the data is sent to the server via the socket output stream. 4, read the service side feedback information. 5, close.   */Import Java.io.*;import Java.net.*; public class Test { public static void main (string[] args) throws Exception  {  socket s = new socket ("localhost", 9999);  FileInputStream fi= new FileInputStream ("c:\\users\\zx\\ Desktop\\1.png ");  byte [] buf = new byte[1024];  OutputStream out = S.getoutputstream ();  InputStream in = S.getinputstream ();  int len;  while ((Len=fi.read (BUF))!=-1)   {   out.write (buf, 0, Len);  }  s.shutdownoutput (); Note here that if you do not add this sentence, the server cannot get-1 because when the local file reaches the end, the data is sent out.   Len =in.read (BUF);  SOP (New String (Buf,0,len));  s.close ();  fi.close ();    }   public static void sop (Object o)  {  System.out.println (o);   }}  import Java.io.*;import java.net.*;p ublic class Zhangxu { public static void main (string[] args) throws  exception& nbsp { serversocket SS = new ServerSocket (9999);  socket s = ss.accept ();  inputsTream in = S.getinputstream (),  outputstream out = S.getoutputstream ();  fileoutputstream fi = new FileOutputStream ("E:\\888.png");  byte [] buf =new byte [1024]; int len; while ((Len=in.read (BUF))!=-1)  {  Fi.write (Buf,0,len);  } out.write ("Upload succeeded". GetBytes ());  sop ("over");  out.close () ;  ss.close ();  s.close ();  fi.close ();  }  public static void sop (Object o)  {   SYSTEM.OUT.PRINTLN (o);   }}    Requirements: Multi-threaded TCP upload pictures.  Import Java.io.*;import Java.net.*; public class Test { public static void main (string[] args) throws Exception  {  while (true)   {  socket s = new socket ("localhost", 8888);  FileInputStream fi= New fileinputs Tream ("C:\\users\\zx\\desktop\\1.png");  byte [] buf = new byte[1024];  OutputStream out = S.getoutputstream () ;  InputStream in = S.getinputstream ();  int len;  while ((Len=fi.read (BUF))!=-1)   {    Out.write (buf, 0, Len); }  s.shutdownoutput (); Note here that if you do not add this sentence, the server cannot get-1 because when the local file reaches the end, the data is sent out.   Len =in.read (BUF);  SOP (New String (Buf,0,len));  s.close ();  fi.close ();  Thread.Sleep (500 ); }  }  public static void sop (Object o)  {  System.out.println (o);   } }   import java.io.*;import java.net.*;p ublic class Zhangxu { public static void main (String[] args ) throws  exception { while (true)  {  ServerSocket ss = new ServerSocket (8888);  Socket s = ss.accept ();  new Thread (new Update (s)). Start ();  SS. Close ();  } }  public static void sop (Object o)  {  System.out.println (o);   } } class Update implements Runnable{ socket s; update (Socket s)  {  this.s=s; }  private static int count =0; public void run ()  {  try  {   inputstream in = S.getinputstream ();   outputstream out = S.getoutputstream ();   fileoutputstream fi = new FileOutputStream ("E:" + count++ + ". png");   byte [] buf =new byte [1024];   int len;   while ((Len=in.read (BUF))!=- 1)    {    Fi.write (buf,0,len);   }   out.write (("Upload successful" +count). GetBytes ());    SYSTEM.OUT.PRINTLN ("Over" +count);   out.close ();   s.close ();    Fi.close (); }  catch (Exception e)   {   &NBSp } }}  

JAVA 24 network communication

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.