[Java Video Note]day23

Source: Internet
Author: User
Tags closing tag

Network programming

Network model: OSI Reference Model, TCP/IP Reference Model

Network communication elements: IP address, port number, transfer Protocol


IP address (corresponding object inetaddress)

Identification of devices in the network

Hard to remember, host name available

Local loopback address: 127.0.0.1 host name: localhost

Import Java.net.*;class day23 {public static void main (string[] args) throws exception{inetaddress i = Inetaddress.getloca Lhost (); SOP (i.ToString ());//Output Gsd/10.10.133.60sop (I.gethostname ());//Output Gsdsop (i.gethostaddress ());// Output 10.10.133.60    focus on mastering inetaddress ia = inetaddress.getbyname ("www.baidu.com"), SOP (Ia.gethostname ()), SOP ( Ia.gethostaddress ());} public static void Sop (Object obj) {System.out.println (obj);}}

Port number

The logical address used to identify the process, and the identity of the different processes

Valid ports: 0~65535, where the 0~1024 system uses or retains ports.

Transport protocol

Rules of Communication

Common protocols: TCP,UDP

Udp

Encapsulates data and sources and purposes into packets without establishing a connection

Limit the size of each datagram within 64K

Because there is no connection, it is an unreliable agreement.

No need to establish connection, fast speed

Tcp

Establish a connection to form a channel for transmitting data.

Make large data transfers in the connection.

Complete connection via three handshake, is a reliable protocol

The connection must be established and the efficiency will be slightly lower

Socket (Network programming is also socket programming)

A socket is a mechanism for network services

Sockets on both ends of the communication

Network communication is actually the communication between sockets

Data is transmitted via IO between two sockets

In the UPD

Datagramsocket socket (socket) for sending and receiving packets

Datagrampacket represents a datagram packet.

Requirement: Send a piece of text data through the UDP transmission mode.

Define a UDP send side

Steps:

1. Establish Udpsocket Service

2. Provide data and encapsulate the data in a packet

3. Send the packet out via the socket service's sending function

4. Close Resources

Import Java.net.*;class udpsend{public static void Main (string[] args) throws EXCEPTION{//1. Create a UDP service, By Datagramsocket object Datagramsocket ds = new Datagramsocket ();//2. Determine data, package into packet//datagrampacket (byte[] buf, int length, inetaddress address, int port) byte[] buf = "UDP is Coming". GetBytes ();D atagrampacket dp = new Datagrampacket (buf, Buf.leng Th, Inetaddress.getbyname ("10.10.133.60"), 10000)//3. Through the socket service, the existing data packets sent out through the Send method Ds.send (DP);//4. Close resource Ds.close ();} public static void Sop (Object obj) {System.out.println (obj);}}

Requirements: Define an application that receives the data transmitted by the UDP protocol and processes the data.

Defining the receive side of UDP

1. Define the Udpsocket service, usually listen to a port, in fact, to the receiving network application to define a digital ID, easy to identify which data come over the application can handle

2. Define a packet because the received byte data is to be stored. Because there are more features in the packet object, you can extract different information from the byte data.

3. The received data is stored in a defined packet via the socket service's Receive method

4. With the unique features of the packet object, these different data are taken out and printed on the console.

5. Close Resources

Import java.net.*;class  udprece{public static void Main (string[] args) throws EXCEPTION{//1. Create a UDP socket service, Establish endpoint Datagramsocket ds = new Datagramsocket (10000);//2. Define a packet for storing data byte[] buf = new byte[1024];D atagrampacket dp = new data Grampacket (buf, buf.length);//3. The received data is stored in the packet Ds.receive (DP) via the Receive method of the service,//4. The data in the packet is obtained by means of the data string IP = Dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0, Dp.getlength ()); int port = Dp.getport (); System.out.println (ip+ "::" +data+ "::" +port);//5. Close Resource Ds.close ();}}

The above we define two applications, the sending and receiving end, two applications can be run independently of the degree. First run the receiving end, at this time the receiving end is waiting to receive the data state, and then run the sending side, at the receiving end of the window will be displayed on the sending side of the message sent.

The following improvements, the sending side can be sent each time the keyboard input a sentence, can be sent multiple times, and the receiving end can also receive multiple times, mainly with a while loop.

Send side:

Import Java.net.*;import java.io.*; Class udpsend2{         publicstatic void Main (string[] args) throws Exception         {                   Datagramsocketds = new Datagramsocket ();                   BUFFEREDREADERBUFR =                            Newbufferedreader (new InputStreamReader (system.in));                   Stringline = null;                    while ((Line= bufr.readline ()) = null)                   {                            if ("886". Equals (line)) break                                     ;                            Byte[]buf = Line.getbytes ();                             DATAGRAMPACKETDP =                                     Newdatagrampacket (buf, Buf.length,                                     inetaddress.getbyname ("10.10.133.60"), 10001);                             Ds.send (DP);                   }                   Ds.close ();         }}
Receiving end:

Import java.net.*;import java.io.*;class udprece2{public static void Main (string[] args) throws exception{ Datagramsocket ds = new Datagramsocket (10001), while (true) {byte[] buf = new byte[1024];D atagrampacket dp = new Datagrampack ET (buf, buf.length);d s.receive (DP); String IP = dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0, Dp.getlength ()); System.out.println (ip+ "....." +data);}}

Write a chat program. There is a part of the data that is collected and the data is sent. These two parts need to be executed at the same time. Then you need to use multithreaded technology. A thread control to receive, a line programmed to send.

Because the receive and send action is inconsistent, define two run methods. And the two methods are encapsulated into different classes.

Import Java.io.*;import Java.net.*;class Send implements Runnable{private Datagramsocket ds; Send (Datagramsocket ds) {this.ds = ds;} public void Run () {Try{bufferedreader bufr = new BufferedReader (new InputStreamReader (system.in)); String line = Null;while ((line = Bufr.readline ())! = null) {if ("886". Equals (line)) break;byte[] buf = line.getbytes ();D Atagrampacket DP = new Datagrampacket (buf, Buf.length, Inetaddress.getbyname ("10.10.133.60"), 10002);d S.send (DP);}} catch (Exception e) {throw new RuntimeException ("Send side Failed");}}} Class Rece implements Runnable{private Datagramsocket ds; Rece (Datagramsocket ds) {this.ds = ds;} public void Run () {Try{while (true) {byte[] buf = new byte[1024];D atagrampacket dp = new Datagrampacket (buf, buf.length);d S. Receive (DP); String IP = dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0, Dp.getlength ()); System.out.println (ip+ "....." +data);} catch (Exception e) {throw new RuntimeException ("Receive end Failed");}}} Class Chatdemo {public static void main (string[] args) throws Exception{datagramsocket Sendsocket = new Datagramsocket ();D atagramsocket recesocket = new Datagramsocket (10002 ); new Thread (New Send (Sendsocket)). Start (); New Thread (New Rece (Recesocket)). Start ();}}

Run:



TCP Transport

Sockets and ServerSocket

Establish client and server side

After the connection is established, the data is transmitted through the IO stream in the socket.

Close socket

Similarly, the client and server side are two separate applications.

Demo TCP Transport

1.TCP sub-client and server side

2. The client corresponds to the socket, and the server-side object is Serversoket.

Client:

By reviewing the Socke object, it is found that when the object is established, it is possible to connect to the specified host. Because TCP is connection-oriented, in the establishment of the socket service, there must be a server-side presence, and the successful connection, the formation of a path, the transmission of data within the channel.

Requirement: Send a text data to the server side

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 ("10.10.133.60", 10003);//In order to send data, you should get the output stream in the Socket stream outputstream out = S.getoutputstream (); Out.write ("TCP is Coming". GetBytes ()); S.close ();}}

Service side:

1. Set up the server-side socket service, ServerSocket (), and listen to a port.

2. Gets the client object that is connected. Through the ServerSocket accept method, no connection will wait, so this method is blocking.

3. If the client sends the data, the server will use the corresponding client object and fetch the read stream to the client object to read the data sent, and print it in the console.

4. Close the server (optional)

Requirements: Define the endpoint to receive data and print it on the console.

Import java.io.*;import java.net.*;class tcpserver{public static void Main (string[] args) throws exception{// Set up the service-side socket service and listen to a port serversocket ss = new ServerSocket (10003);//Get the client object from the link via the Accept method socket S = ss.accept (); String IP = s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connect");//Gets the data sent by the client,//to read the data using the Read stream method of the client object InputStream in = S.getinputstream (); [] buf = new Byte[1024];int len =in.read (BUF); System.out.println (New String (buf, 0, Len)); S.close ();//Close client Ss.close ();}}

At this point the server only accepts data and prints it on the console, and no return action has been made.

The following shows the exchange of clients and service-side transfers for TCP.

Requirements: The client sends data to the server, and after the server receives it, it gives feedback to the client.

Client:

1. Set up the socket service to specify the host and port to connect to.

2. Gets the output stream in the socket stream, writes the data to the stream, and sends it over the network to the server.

3. Gets the input stream in the socket stream, obtains the data from the server-side feedback, and prints it.

4. Close the client resource.

Client code:

Import Java.net.*;import java.io.*;class  tcpclient2{public static void Main (string[] args) throws Exception{socket s = new Socket ("10.10.133.60", 10004), outputstream out = S.getoutputstream (); Out.write ("Hello, service side!". GetBytes ()); InputStream in = S.getinputstream (); byte[] buf = new Byte[1024];int len = In.read (BUF);//blocking method, waiting for the server side to return data. System.out.println (New String (buf, 0, Len)); S.close ();}}

Server-side code:

Import Java.io.*;import java.net.*;class TcpServer2 {public static void main (string[] args) throws exception{ ServerSocket ss = new ServerSocket (10004); Socket s = ss.accept (); String IP = s.getinetaddress (). gethostaddress (); System.out.println (ip+ "... connect"), InputStream in = S.getinputstream (); byte[] buf = new Byte[1024];int len = In.read ( BUF); System.out.println (New String (buf, 0, Len));//return data outputstream out = S.getoutputstream (); Out.write ("Roger that!". GetBytes ()); S.close (); Ss.close ();}}

Requirements: Establish a text conversion server. The client sends text to the server, and the server turns the text into uppercase and back to the client. And the client can continue the text conversion, when the client input over, the conversion is over.

Analysis:

Client: Since it is the operation of the data on the device, you can use IO technology for a long time and think in accordance with the operational rules of IO.

Source: Keyboard entry. Purpose: Network device, network output stream. And the text data is manipulated, you can select a character stream.

Steps:

1. Service Creation

2. Get Keyboard entry

3. Send data to the server

4. Gets the uppercase data returned by the server.

5. Close the resource.

Are text data that can be manipulated using a character stream while increasing efficiency and adding buffering.

Import Java.io.*;import java.net.*;class transclient {public static void main (string[] args) throws exception{socket s = n EW Socket ("10.10.133.60", 10005);//defines the stream object that reads the keyboard data BufferedReader bufr = new BufferedReader (New InputStreamReader ( system.in));//define the purpose, write data to the socket output stream, send to the server bufferedwriter bufout = new BufferedWriter (New OutputStreamWriter ( S.getoutputstream ()));//defines a socket read stream that reads the capitalization information of the reverse back of the server BufferedReader Bufin = new BufferedReader (New InputStreamReader ( S.getinputstream ())); String line = null;while (line = Bufr.readline ()) = null)//Read keyboard {if ("over". Equals (line)) Break;bufout.write (line);// Send the data before the carriage return to bufout.newline ();//So write this sentence bufout.flush ();//NOTE!! String str = bufin.readline ();//reads the server-side return information System.out.println ("Server:" +str); Bufr.close (); S.close ();}}

Service side:

Source: Socket Read stream. Purpose: the socket output stream. It's all text and decorations.

Import Java.io.*;import java.net.*;class  transserver{public static void Main (string[] args) throws exception{ ServerSocket ss = new ServerSocket (10005); Socket s = ss.accept (); String IP = s.getinetaddress (). gethostaddress (); System.out.println (ip+ ". Connect ");//Read the data in the socket read stream BufferedReader Bufin = new BufferedReader (New InputStreamReader (S.getinputstream ()));// Purpose: the socket output stream. Writes uppercase data to the socket output stream and//sends to the client bufferedwriter bufout = new BufferedWriter (New OutputStreamWriter (S.getoutputstream ())); String line = null;while (line = Bufin.readline ())! = null) {System.out.println (line); Bufout.write (Line.touppercase ()) ; Bufout.newline ();//This is the end tag Bufout.flush ();} S.close (); Ss.close ();}}

The problem arises from this example:

Phenomenon:

The client and server side are waiting in inexplicable. Why is it? Because both the client and the server have a blocking approach. These methods do not read to the closing tag. Then it will wait all the time and cause both ends to wait.


Simplify Your code:

The BufferedWriter bufout = new BufferedWriter (

Newoutputstreamwriter (S.getoutputstream ()));

Change to printwriter out = new PrintWriter (S.getoutputstream (), true); True to set automatic refresh

Will

Bufout.write (Line.touppercase ());

Bufout.newline ();//This is the end tag

Bufout.flush ();

Changed to a sentence: Out.println (Line.touppercase ());

Run:



Example:

The client passes one file to the server, and the server reads the file and saves it as another file.

Client:

Import Java.io.*;import java.net.*;class  textclient{public static void Main (string[] args) throws ioexception{ Socket s = new socket ("10.10.133.60", 10006); BufferedReader bufr = new BufferedReader (New FileReader ("Tcpclient.java")); PrintWriter out = new PrintWriter (S.getoutputstream (), true); String line = null;while (line = Bufr.readline ())! = null) {out.println (line);} S.shutdownoutput ();//closes the client output stream, which is equivalent to adding an end tag to the//stream BufferedReader Bufin = new BufferedReader (New InputStreamReader ( S.getinputstream ())); String str = bufin.readline (); System.out.println (str); Bufr.close (); S.close ();}}

Service side:

Import Java.io.*;import java.net.*;class  textserver{public static void Main (string[] args) throws exception{ ServerSocket ss = new ServerSocket (10006); Socket s = ss.accept (); String IP = s.getinetaddress (). gethostaddress (); System.out.println (ip+ ". Connect "); BufferedReader Bufin = new BufferedReader (New InputStreamReader (S.getinputstream ())); PrintWriter out = new PrintWriter (New FileWriter ("Server.txt"), true); String line = null;while (line = Bufin.readline ())! = null) {out.println (line);} PrintWriter pw = new PrintWriter (S.getoutputstream (), True);p w.println ("Upload succeeded!"); o Ut.close (); S.close (); Ss.close ();}}

Run:









[Java Video Note]day23

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.