Java Fundamentals 9: Network programming

Source: Internet
Author: User

On the Java foundation of the article, I think it can also be written in my other blog, is definitely original, and now share to everyone out.

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- ---------

I. Overview


Note: Before the soft test summed up an article on the basic knowledge of the network, we can refer to http://blog.csdn.net/jin870132690/article/details/41597135


As long as people who have access to the network do not know the importance of the network, network programming refers to the writing of other computers to communicate with the program. Java has encapsulated the things that a network program needs into different classes. Greatly simplifies the difficulty of our programming.

1. Network Model

The network model includes the OSI seven-layer model and the TCP\IP model


2. Communication Elements1. IP address

It is a device identification in the network, divided into IPv4 and IPv6, common IP4 address sub-ABC three categories

The corresponding class of IP address in Java is inetaddress

<span style= "FONT-SIZE:14PX;" >//gets the local hostname inetaddress IP = inetaddress.getlocalhost ();//based on hostname or IP, obtain IP Address IP = inetaddress.getbyname (" Www.baidu.com ");//Sometimes the host may not be unique, with getallbyname ();//inetaddress[] ip2 = Inetaddress.getallbyname (Ip.gethostname ());// for (inetaddress inetaddress:ip2) {//system.out.println (inetaddress); SYSTEM.OUT.PRINTLN ("Address:" + ip.gethostaddress ()); System.out.println ("Name:" + ip.gethostname ());</span>


2. Port number

The port number is used to identify the different processes, the valid port number is 0-65535, where 0-1024 is the system use or retain the port number, try not to use

3. Communication protocol

That is, communication rules, including TCP and UDP protocols


UDP is a non-connection-oriented protocol that does not establish a connection with the other, but sends the packet over directly. Suitable for applications where only a small amount of data is transmitted at a time and the reliability requirements are low

Commonly used in UDP connection, such as online video voice chat application environment, low reliability requirements, the loss of a bit of data does not matter.


TCP is a connection-based protocol, which means that three handshakes are performed before the data is formally sent and sent to ensure a reliable connection with the other party.

The TCP protocol can provide a reliable communication connection for the application, and the data communication system with high reliability requirements often uses the TCP protocol.

TCP protocol is generally used for file transfer, send and receive mail and other data accuracy requirements of the activity.


Second, UDP transmission
1, the receiving end and the sending side of the interaction processReceiving Packets

A, create the send side via Datagramsocket

b, the data to be sent is encapsulated in the Datagrampacket package

c, called by the Send method.

Receiving Packets

A, create a receive end via Datagramsocket

b, encapsulating the data received in the Datagrampacket package

C, receiving packets via recive


2. Example: Chat room

Receiving end

<span style= "FONT-SIZE:14PX;" >package Jinfulin. Udp. Demo;import Java.io.ioexception;import Java.net.datagrampacket;import Java.net.datagramsocket;public class Udpredemo {/* * requirements: Create receive end and receive text analysis:  * 1, set up socket service,  * 2, Build packet Package *  3, Package received data in packet *   4, read contents of package * 5, Close service */public static void Main (string[] args) throws IOException {System.out.println ("Receive Side started"), while (true)//Receive end always starts {// 1, Establish socket service Datagramsocket ds = new Datagramsocket (12000);//2, Build Packet package byte[] buf = new byte[1024];D atagrampacket dp = NE W Datagrampacket (buf, buf.length);//3, receiving packet Ds.receive (DP);//4, reading the contents of the package string IP = dp.getaddress (). gethostaddress (); /String name = Dp.getaddress (). GetHostName ();//int pot = Dp.getport (); String txt = new string (Dp.getdata (), 0, Dp.getlength ()); SYSTEM.OUT.PRINTLN (IP + ":::::" + txt); Ds.close ();}}} </span>



Send Side

<span style= "FONT-SIZE:14PX;" >package Jinfulin. Udp. Demo;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.inetaddress;public class UDPSendDemo {/* * required:  Create send side and send text * idea: 1, set up socket service * 2, set up data sent * 3, package sent data in packet package * 4, send data * 5, close * */public static void Main (string[] args) Throws IOException {System.out.println ("Send side Started"),//1, establishing socket service Datagramsocket ds = new Datagramsocket (8888); BufferedReader bufr = new BufferedReader (new InputStreamReader (system.in)); String line = Null;while ((line = Bufr.readline ()) = null) {//2, establishes the data sent//string str = "Jinfoling";//byte[] buf = Str.getbytes (); byte[] buf = line.getbytes ()//3, the data sent is encapsulated in the packet package Datagrampacket DP = new Datagrampacket (Buf,buf.length, Inetaddress.getbyname ("110.251.19.2"), 12000);//, Send data Ds.send (DP), if ("over". Equals (line)) {break;}} 5, close Ds.close ();}} </span>




Third, TCP transmission
1. Socket and ServerSocket1,socket

Socket is the meaning of sockets, you can also understand it as a socket or port.

Sockets are used to connect an application to a port and are an imaginary connection device.




2,serversocket

ServerSocket represents a server-side socket whose primary function is to wait for a network request, which can wait for a connected socket through the established port.




2, the server and client interaction process


A, the server creates a serversocket and calls the Accept () method to wait for the client.

B, the client creates a socket request to connect with the user.

C, the server receives the client's request, while establishing a new socket to establish contact with the customer, the server continues to wait for the new request


3. Example (upload image):

Client

<span style= "FONT-SIZE:14PX;" >package Jinfulin. Tcp. Test.uploadpic;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import Java.io.bufferedreader;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.InputStream; Import java.io.inputstreamreader;import java.io.outputstream;import java.net.socket;/* * Upload a picture of the client */public class uploadpicclient {///idea://1, create socket (socket)//2, create Source: Local picture//3, create destination: Server-side//4, add buffer will write to stream//5, create read stream//6, read the data returned by the servers//7, Close resource public static void main (string[] args) throws IOException {//1, create socket (socket) socket s = new socket ("127.0.0.1", 8881);// 2. Create Source: A local picture fileinputstream pic = new FileInputStream ("f:\\111.jpg");//3, creation Purpose: server (output stream) outputstream out = S.getoutputstream (); Bufferedoutputstream bufout = new Bufferedoutputstream (out);//4, plus buffer will be written to stream bufferedinputstream Bufin = new Bufferedinputstream (pic); int ch = 0;while ((ch = bufin.read ())! =-1) {//out.write (ch); bufout.write (ch);} ----Tell the server that it has finished writing s.shutdownoutput ();//5, create an input stream inputstream in = S.getinpUtstream ();//6, reads the data returned by the server BufferedReader bufr =new bufferedreader (New InputStreamReader (in)); String line = Bufr.readline (); System.out.println (line);//7, close Resource bufin.close (); Bufr.close ();p ic.close (); S.close ();}} </span>

Service side

<span style= "FONT-SIZE:14PX;" >package Jinfulin. Tcp. Test.uploadpic;import Java.io.ioexception;import Java.net.serversocket;import Java.net.Socket;public class uploadpicserver {public static void main (string[] args) throws IOException {//1, creating a service-side socket Serversocketserversocket SS = new S Erversocket (8881); while (true) {//2, gets the client socket s = ss.accept (); New Thread (New Uploadtask (s)). Start (); Ss.close ();}} </span>

Methods called by the service side

<span style= "FONT-SIZE:14PX;" >package Jinfulin. Tcp. Test.uploadpic;import Java.io.bufferedinputstream;import Java.io.file;import Java.io.fileoutputstream;import Java.io.inputstream;import java.io.outputstream;import java.net.socket;/** * @author Jinfoling * */public class UpLoadTask Implements Runnable {private socket s;public Uploadtask (Socket s) {super (); this.s = s;} public void Run () {try {//2.1 gets the IP address, ip print string ip = s.getlocaladdress (). gethostaddress (); String name = S.getlocaladdress (). GetHostName (); SYSTEM.OUT.PRINTLN (IP + "....");//3, Source: Gets the data sent by the client (output stream) InputStream in = S.getinputstream ();//4, Purpose: Writes the read to a directory file dir = new File ("f:\\" + name), if (!dir.exists ()) dir.mkdirs (); File File = new file (dir, "server.jpg"); FileOutputStream fos = new FileOutputStream (file);//5, loop writes int ch = 0; Bufferedinputstream Bufin = new Bufferedinputstream (in), while ((ch = bufin.read ())! =-1) {fos.write (ch);} 6. Get the output stream of socket, return "upload success" to client outputstream out = S.getoutputstream (); Out.write ("Upload succeeded!". GetBytes ());//7, close the capitalSource Bufin.close (); Fos.close (); S.close ();} catch (Exception e) {}}}</span>


Iv. URL Class


The class URL represents a Uniform resource locator, which is a pointer to the Internet "resource". A resource can be a simple file or directory, or a reference to a more complex object, such as a query to a database or search engine.

A URL class can resolve a client's request to a service-side

Common methods

String Getprotocol ();//Get Protocol name

String gethost ();//Get host Name

int Getport ();//Get Port number

String getFile ();//Get URL file name

String GetPath ();//Gets the path portion of this URL

String getquery ();//Gets the query part of this URL

Example:

<span style= "FONT-SIZE:14PX;" ><span style= "White-space:pre" ></span>string str_url = "http://127.0.0.1:8080/myweb/1.html"; URL url = new URL (str_url); InputStream in = Url.openstream (); byte[] buf = new Byte[1024];int len = In.read (BUF); String text = new string (Buf,0,len); System.out.println (text); In.close ();</span>


V. Last


There is a lot of knowledge about the network, Java is mainly used in web development, we need to practice in the future.













Java Fundamentals 9: Network programming

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.