Java basics: Network Programming

Source: Internet
Author: User

Java basics: Network Programming

 

 

I. Overview

 

Note: I have summarized an article about network in my previous soft exams. For details, refer to www.bkjia.com.

People who have been in touch with the network will not be unaware of the importance of the network. network programming refers to programming to communicate with other computers. Java has encapsulated the things required by network programs into different classes. It greatly simplifies the difficulty of programming.

1. Network Model

The network model includes the OSI Layer-7 model and the TCPIP model.

2. communication element 1. IP Address

It is a device identifier in the network, divided into ipv4 and ipv6, the common ip4 address is divided into ABC three types

The corresponding class of the IP address in java is InetAddress.

 

// Obtain the local host name InetAddress ip = InetAddress. getLocalHost (); // obtain ip address = InetAddress Based on the host name or ip address. getByName (www.baidu.com); // sometimes the host may not be unique. Use 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 ());


 

2. Port Number

The port number is used to identify different processes. The valid port number is 0-65535. 0-indicates the system uses or retains the port number.

3. Communication Protocol

Communication rules, including TCP and UDP

 

UDP is a non-connection-oriented protocol. It directly sends packets instead of establishing a connection with the other party. Applicable to applications that transmit only a small amount of data at a time and have low reliability requirements

It is often used in UDP connections, such as online video and voice chat applications. It has low reliability requirements and does not matter if data is lost.

 

TCP is a connection-based protocol. That is to say, before sending and receiving data, three handshakes should be performed to ensure a reliable connection with the other party.

TCP can provide reliable communication connections for applications. Data Communication Systems with high reliability requirements often use TCP to transmit data.

TCP is generally used for activities that require high data accuracy, such as file transmission, sending and receiving emails, etc.

 

Ii. UDP Transmission 1. the receiving end receives data packets during interaction with the sending end

A. Create a sender using mongoramsocket

B. encapsulate the data to be sent in the mongorampacket packet package.

C. Call the send method to send the message.

Receive data packets

A. Create an acceptor through mongoramsocket

B. encapsulate the received data in the initrampacket packet package.

C. receive packets through recive

 

2. Example: chat room

Acceptor

 

Package jinfulin. UDP. demo; import java. io. IOException; import java.net. datagramPacket; import java.net. required ramsocket; public class UDPReDemo {/** requirement: Create an acceptor and receive text analysis: * 1. Create a socket service, * 2. Create a packet package * 3, encapsulate the received data in packet * 4, read the package content * 5, disable the Service */public static void main (String [] args) throws IOException {System. out. println (the receiving end has been started); while (true) // the receiving end has been started {// 1, and the socket service has been established; new DatagramSocket ds = new DatagramSocket (12000); // 2, create a packet package byte [] buf = new byte [1024]; DatagramPacket dp = new DatagramPacket (buf, buf. length); // 3, receives data packets ds. receive (dp); // 4, read the content in 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 ();}}}


 

 

Sender

 

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 {/** requirement: Create the sender and send text * idea: 1. Create socket Service * 2. Create sent data * 3, encapsulate the sent data in the packet package ** 4. Send the data ** 5. Disable **/public static void main (String [] args) throws IOException {System. out. println ( The sender has started); // 1, establish the socket service initramsocket ds = new initramsocket (8888); BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); String line = null; while (line = bufr. readLine ())! = Null) {// 2, create the sent data // String str = Jin Fulin; // byte [] buf = str. getBytes (); byte [] buf = line. getBytes (); // 3. encapsulate the sent data in the packet package; then rampacket dp = new DatagramPacket (buf, buf. length, InetAddress. getByName (110.251.19.2), 12000); //, send data ds. send (dp); if (over. equals (line) {break ;}// 5, disable ds. close ();}}


 

 

 

Iii. TCP transmission 1. Socket and ServerSocket1, Socket

Socket means Socket. You can also regard it as a Socket or port.

A socket is used to connect an application to a port. It is a hypothetical connection device.

 

 

2, ServerSocket

ServerSocket indicates the socket on the server. Its main function is to wait for network requests. It can wait for the connected socket through a specified port.

 

 

 

2. Interaction between the server and the client

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 to the user.

C. The server receives client requests and establishes a new Socket to connect with the customer. The server continues to wait for new requests.

 

3. Example (upload an image ):

Client

 

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;/** client for uploading images */public class UpLoadpicClient {// thought: // 1. Create a Socket (Socket) // 2. Create a source: A local image // 3. Creation purpose: Server // 4. Add a buffer to write data to the stream // 5, create a read stream // 6, read the data returned by the server // 7, and disable the public static void main (String [] args) resource) throws IOException {// 1, create Socket (Socket) Socket s = new Socket (127.0.0.1, 8881); // 2, create Source: A local image FileInputStream pic = new FileInputStream (f: \ 111.jpg); // 3. Creation purpose: Server (output stream) OutputStream out = s. getOutputStream (); BufferedOutputStream bufout = new BufferedOutputStream (out); // 4. The buffer will be added to BufferedInputStream bufIn = new BufferedInputSt. Ream (pic); int ch = 0; while (ch = bufIn. read ())! =-1) {// out. write (ch); bufout. write (ch);} // ---- tell the server that s has been written here. shutdownOutput (); // 5, create the input stream InputStream in = s. getInputStream (); // 6, read the data returned by the server BufferedReader bufr = new BufferedReader (new InputStreamReader (in); String line = bufr. readLine (); System. out. println (line); // 7. Disable the resource bufIn. close (); bufr. close (); pic. close (); s. close ();}}

 

Server

 

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, create server Socket ServerSocketServerSocket ss = new ServerSocket (8881); while (true) {// 2, obtain the Socket s = ss of the client. accept (); new Thread (new UpLoadTask (s )). start ();} // ss. close ();}}

Method called by the server

 

 

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 Jin Fulin **/public class UpLoadTask implements Runnable {private Socket s; public UpLoadTask (Socket s) {super (); this. s = s;} public void run () {try {// 2.1 get the ip address, and the ip prints String ip = s. getlocaladsid Ss (). getHostAddress (); String name = s. getLocalAddress (). getHostName (); System. out. println (ip + ....); // 3, source: get data from the client (output stream) InputStream in = s. getInputStream (); // 4, objective: to write the read File 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, write int ch = 0 cyclically; BufferedInputStream bufIn = new BufferedInputStream (in ); while (ch = bufIn. read ())! =-1) {fos. write (ch);} // 6. Obtain the Socket output stream and return the uploaded data to the client OutputStream out = s. getOutputStream (); out. write (upload successful !. GetBytes (); // 7, close the resource bufIn. close (); fos. close (); s. close () ;}catch (Exception e ){}}}


 

Iv. URL

 

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 of a database or search engine.

The URL class can parse the requests sent from the client to the server.

Common Methods

String getProtocol (); // obtain the protocol name

String getHost (); // obtain the Host Name

Int getPort (); // get the port number

String getFile (); // get the URL File Name

String getPath (); // obtain the path of this URL

String getQuery (); // obtain the query part of this URL

Example:

 

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();


 

 

 

 

 

 

 

 

 

Related Article

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.