Java getting started -- (8) network programming, java getting started Network Programming

Source: Internet
Author: User
Tags dedicated ip

Java getting started -- (8) network programming, java getting started Network Programming
Key words: IP address, port, UDP, initrampacket, initramsocket, TCP, ServerSocket, Socket, File Upload I. Basic Concepts 1. Basic Concepts ① MAC: media Access Control (MAC) or Medium Access Control address is a Media Access Control address, or a physical address or hardware address, used to define the location of a network device. In the OSI model, the layer-3 network layer is responsible for IP addresses, while the layer-2 data link layer is responsible for MAC addresses. Therefore, a host has a MAC address, and each network address has a dedicated IP address. ② IP Address: refers to the Internet Protocol Address (Internet Protocol Address), which is short for IP Address. An IP address is a Unified IP address format provided by the IP protocol. It allocates a logical address to each network and each host on the Internet to shield the differences between physical addresses. There are still some ip proxy software, but most of them are charged.

TCP/IP network mode

 

Application Layer

Such as HTTP, FTP, DNS

Transport Layer

Such as TCP and UDP

Network Layer

Such as IP, ICMP, and IGMP

Chain saw Layer

Such as drivers and interfaces

③ Port: it can be considered as the exit for communication between the device and the outside world. The port number is expressed in two bytes (16-bit binary number), and its value range is 0 ~ 65 535, 0 ~ The port number between 1023 is used for the following well-known network services and applications. The user's common application needs to use the port number above 1024. Ports are divided into physical ports and logical ports (numerical identification of software applications ).

④ TCP (Transmission Control Protocol) and UDP (User datasync Protocol) Protocols belong to the transport layer Protocol.

TCP is a connection-oriented communication protocol that provides reliable data transmission in an IP environment. Its services include data stream transmission, reliability, effective traffic control, full-duplex operations, and multiplexing. Send data packets through connection-oriented, end-to-end, and reliable data packets. In general, it opens a connection channel for the sent data before sending the data;

⑤ UDP is a wireless communication protocol and does not provide reliability, throttling, or error recovery for IP addresses.

 

2. Examples of common InetAddress methods:
1 public class Example1 {2 public static void main (String [] args) throws Exception {3 // create an InetAddress object 4 InetAddress localAddress = InetAddress of the local host.GetLocalHost(); 5 // get the InetAddress object of the specified host 6 InetAddress remoteAddress = InetAddress.GetByName("Www.itcast.cn"); 7 // obtain the Host Name of the IP address. 8 System. out. println ("local IP Address:" + localAddress.GetHostName(); 9 // obtain the original IP address in string format 10 System. out. println ("itcast IP Address:" + remoteAddress.GetHostAddress(); 11 // determine whether the address can reach 12 System. out. println ("3 seconds:" + remoteAddress.IsReachable(3000); 13 14 System. out. println ("The itcast host name is:" + remoteAddress. getHostName (); 15} 16}

Running result:

Local IP Address: wrt. localitcast IP Address: 123.57.45.993 seconds: falseitcast Host Name: www.itcast.cn

 

Ii. UDP Communication

1. DatagramPacket

This type is similar to a container. The constructor method used when creating the sender rampacket object at the sender and receiver is different. The constructor method at the receiver only needs to receive a byte array to store the received data, the sender's constructor not only needs to receive the byte array containing sent data, but also needs to specify the sender's IP address and port number.

DatagramPacket constructor:

① DatagramPacket (byte [] buf, int length)

Used at the acceptor to specify the byte array and data size of encapsulated data when creating an initrampacket object.

② DatagramPacket (byte [] buf, int length, InetAddress addr, int port)

Used by the sender. when creating the initrampacket object, it specifies the byte array of the encapsulated data, the data size, the destination IP address (addr) of the data packet, and the port number (port ).

③ DatagramPacket (byte [] buf, int offset, int length)

Used at the acceptor to specify the byte array, data size, and start position of the encapsulated data when creating the initrampacket object. The offset parameter is used to specify that the received data starts from the offset when it is placed in the buf buffer array.

④ DatagramPacket (byte [] buf, int offset, int length, InetAddress addr, int port)

Used by the sender. when creating the initrampacket object, it specifies the byte array of the encapsulated data, the data size, the destination IP address (addr) of the data packet, and the port number (port ). The offset parameter is used to specify the offset for sending data, that is, sending data from the offset position.

Common methods in the DatagramPacket class
Method Declaration Function Description
InetAddress getAddress () This method is used to return the IP address of the sender or receiver. If the sender rampacket object is sent, the IP address of the receiver is returned. Otherwise, the IP address of the sender is returned.
Int getPort () This method is used to return the port number of the sender or receiver. If the sender rampacket object is sent, the receiver port number is returned. Otherwise, the sender port number is returned.
Byte [] getData () This method is used to return the data to be received or to be sent. If it is a sender's initrampacket object, the data to be sent is returned. Otherwise, the received data is returned.
Int getLength () This method is used to return the length of the data to be received or to be sent. If it is a sender's initrampacket object, the length of the data to be sent is returned. Otherwise, the length of the received data is returned.

2. DatagramSocket

Mongoramsocket is similar to the dock. The instance object can send and receive mongorampacket data packets. The construction method used when creating the mongoramsocket object at the sender and receiver is different.

DatagramSocket construction method:

① DatagramSocket ()

When you create a sender ramsocket object, no port is specified when you create the object. At this time, the system allocates a port number that is not used by other network programs.

② DatagramSocket (int port)

This method can be used to create the initramsocket object at the receiving end, and to create the initramsocket object at the sending end,When creating an acceptor's initramsocket object, you must specify a port number to listen to the specified port.

③ DatagramSocket (int port, InetAddress addr)

This constructor not only specifies the port number, but also the IP address. This method is applicable when multiple NICs are computed.

Common methods in the DatagramSocket class
Method Declaration Function Description
Void receive (DatagramPacket p) This method is used to fill the received data into the initrampacket data packet. It will remain in the blocking state until the data is received. This method will only return when the data packet is received.
Void send (DatagramPacket p) This method is used to send mongorampacket packets. The sent data packet contains the data to be sent, the data length, the IP address and port number of the remote host.
Void close () Close the current Socket and notify the driver to release the resources reserved for this Socket.

3. UDP Network Program

During communication, only the receiving end program runs first to avoid data loss because the data sent by the sending end cannot be received. Example:

1 import java.net. datagramPacket; 2 import java.net. datagramSocket; 3 4 // receiver program 5 public class Example2 {6 public static void main (String [] args) throws Exception {7 // create a 1024-byte array, used to receive data 8 byte [] buf = new byte [1024]; 9 // defines a initramsocket object, and the listening port is 895410 initramsocket ds = new initramsocket (8954 ); 11 // define a DatagramPacket object for receiving data 12 DatagramPacket dp = new DatagramPacket (buf, 1024); 13 System. Out. println ("waiting for receiving data"); 14 ds. receive (dp); // wait for receiving data. If no data exists, it will block 15 // call the DatagramPacket method to obtain the received message, including content, length, IP address, and port number 16 String str = new String (dp. getData (), 0, dp. getLength () 17 + "from" + dp. getAddress (). getHostAddress () + ":" + dp. getPort (); 18 System. out. println (str); // print the received information 19 ds. close (); // release resource 20} 21} 22 23 24 import java.net. export rampacket; 25 import java.net. export ramsocket; 26 import java.net. inetAddress; 27 28 // sender program 29 public class Example3 {30 public static void main (String [] args) throws Exception {31 // create a initramsocket object 32 initramsocket ds = new initramsocket (3000); 33 String str = "Hello World! "; // The data to be sent 34/* 35 * create a data packet to be sent, including the sent data, data length, acceptor IP address and port number 36 */37 DatagramPacket dp = new DatagramPacket (str. getBytes (), str. length (), 38 InetAddress. getByName ("localhost"), 8954); 39 System. out. println ("Send message"); 40 ds. send (dp); // send data 41 ds. close (); // release resource 42}

Running result

Send message waiting for receiving data Hello World! From127.0.0.1: 3000

Resolution: before sending the goods (data), determine whether the terminal can receive the goods.

Create a space (Data container) to receive the goods (data), create the terminal [container ramsocket (8954)], and monitor the delivery channel (port) of the Shipping Terminal in real time ), create a container and add the space to receive the cargo. Wait until the Receiving Terminal fills the cargo in the container and obtains the cargo information (data and other information ).

To send goods, you need to build a terminal [container ramsocket (3000)]. The terminal can specify the sending channel as the port (or the sending channel without specifying the sending channel) and load the goods (data) into the container (container rampacket ).

), And specify the name (IP address or host name) and the receiving channel (port) to send the container to [send ()] through the terminal to free up space (close ).

 

Iii. TCP Communication

1. ServerSocket

When developing a TCP program, you must first create a server program. The construction method is as follows:

① ServerSocket ()

Using this constructor, The ServerSocket object is not bound to a port number and cannot be used directly. You need to call the bind (SocketAddress endpoint) method to bind it to the specified port, can be used normally.

② ServerSocket (int port) [most common]

You can use this constructor to bind a ServerSocket object to a specified port number.

③ ServerSocket (int port, int backlog)

The backlog parameter is used to specify the number of customers waiting for connection requests when the server is busy. If this parameter is not specified, the default value is 50.

④ ServerSocket (int port, int backlog, InetAddress bindAddr)

A related IP address is specified, which is applicable when multiple NICs and multiple IP addresses exist on the computer.

Common Methods in ServerSocket class
Method Declaration Function Description
Socket accept () This method is used to wait for a connection from the client. The connection is blocked until the client is connected. If a client is connected, a corresponding Socket object is returned.
InetAddress getInetAddress () This method is used to return an InetAddress object, which encapsulates the IP address bound to ServerSocket.
Boolean isClosed () This method is used to determine whether the ServerSocket object is closed. If it is closed, true is returned. Otherwise, false is returned.
Void bind (SocketAddress endpoint) This method is used to determine whether a ServerSocket object is bound to a specified IP address and port number. The endpoint parameter encapsulates the IP address and port number.

2. Socket

Common Socket constructor: ① Socket () uses this constructor to create a Socket object without specifying the IP address and port number. After the object is created, you must call the connect (SocketAddress endpoint) method, the endpoint encapsulates the IP address and port number. ② Socket (String host, int port) uses this constructor to connect the server program running on the specified IP address and port according to the parameters when creating the Socket object, the host parameter receives a character-type IP address. ③ Socket (InetAddress addres, int port) is similar to the second constructor. The address parameter is used to receive an InetAddress-type object, which encapsulates an IP address.
Common Methods in Socket classes
Method Declaration Function Description
Int getPort () This method returns an int type object. The port number connecting the Socket object to the server
InetAddress getLocalAddress () This method is used to obtain the local IP address bound to the Socket object and encapsulate the IP address into an InetAddress type object to return
Void close () This method is used to close the Socket connection and end the communication. Before closing the Socket, close all input and output streams related to the Socket. This is because a good program should release all resources when execution is complete.
IputStream getInputStream () This method returns an InputStream input stream object. If the object is returned by a Socket on the server side, it is used to read the data sent by the client. Otherwise, it is used to read the data sent by the server.
OutputStream getOutputStream () This method returns an output stream object of the OutputStream type. if the object is returned by a Socket on the server side, it is used to send data to the client. Otherwise, it is used to send data to the server side.
3. Simple TCP network program
1 import java. io. outputStream; 2 import java.net. serverSocket; 3 import java.net. socket; 4 5 public class Example4 {6 public static void main (String [] args) throws Exception {7 new TCPServer (). listen (); // create the TCPServer object and call the listen () method 8} 9} 10 // TCP server side 11 class TCPServer {12 private static final int PORT = 7788; // define a port number 13 14 public void listen () throws Exception {// define a listen () method and throw an Exception 15 ServerSoc Ket serverSocket = new ServerSocket (PORT); // create a ServerSocket object 16 Socket client = serverSocket. accept (); // call the accept () method of ServerSocket to receive data 17 OutputStream OS = client. getOutputStream (); // get the output stream of the client 18 System. out. println ("starting to exchange data with the client"); 19 OS. write ("Java welcome! "). GetBytes (); 20 Thread. sleep (5000); // simulate the time it takes to execute other functions 21 System. out. println ("End interaction data with the client"); 22 OS. close (); 23 client. close (); 24} 25}

 

1 import java. io. inputStream; 2 import java.net. inetAddress; 3 import java.net. socket; 4 5 public class Example5 {6 public static void main (String [] args) throws Exception {7 new TCPClient (). connect (); // create a TCPClient object and call the connect () method 8} 9} 10 // TCP client 11 class TCPClient {12 private static final int PORT = 7788; // server port 13 public void connect () throws Exception {14 // create a Socket and connect it to the computer with the given address and port number 15 Socket client = new Socket (InetAddress. getLocalHost (), PORT); 16 InputStream is = client. getInputStream (); // get the received data stream 17 byte [] buf = new byte [1024]; // defines the buffer of the 1024 byte array 18 int len = is. read (buf); // read data to the buffer 19 System. out. println (new String (buf, 0, len); // outputs the data in the buffer to 20 clients. close (); // close the Socket object and release the resource 21} 22}

 

Example4 running result: Start to exchange data with the client end to interact with the client Example5 running result: Java welcome!

 

4. TCP case-file upload

Allows you to upload images to the server.

Server program:

1 import java. io. file; 2 import java. io. fileOutputStream; 3 import java. io. inputStream; 4 import java. io. outputStream; 5 import java.net. serverSocket; 6 import java.net. socket; 7 8 public class Example7 {9 public static void main (String [] args) throws Exception {10 ServerSocket serverSocket = new ServerSocket (10001 ); // create the ServerSocket object 11 while (true) {12 // call the accept () method to receive client requests. Obtain the Socket object 13 Socket s = ServerSocket. accept (); 14 // each time a Socket connection is established with the client, a separate Thread is enabled to process the interaction with the client 15 new Thread (new ServerThread (s )). start (); 16} 17} 18} 19 class ServerThread implements Runnable {20 private Socket socket; // hold a Socket type attribute 21 public ServerThread (Socket socket) {// In the constructor, pass the Socket object as the real parameter 22 this. socket = socket; 23} 24 25 @ Override26 public void run () {27 String ip = socket. getInetAddress (). getHostAddress (); // obtain the IP address of the client 28 I Nt count = 1; // Number of uploaded images 29 try {30 InputStream in = socket. getInputStream (); 31 // create the File object 32 File parentFile = new File ("/Users/adims/Downloads/upload/"); 33 if (! ParentFile. exists () {// if it does not exist, create this directory 34 parentFile. mkdir (); 35} 36 // use the Client IP address as the File name for outgoing files. 37 file File = new File (parentFile, ip + "(" + count + "2.16.jpeg"); 38 while (file. exists () {39 // if the file name exists, set count ++ 40 File = new file (parentFile, ip + "(" + (count ++) + "pai.jpeg"); 41} 42 // create a FileOutputStream object 43 FileOutputStream fos = new FileOutputStream (file); 44 byte [] buf = new byte [1024]; // define a byte array 45 int len = 0; // define an int type variable len, The initial value is 046 while (len = in. read (buf ))! =-1) {// cyclically read data 47 fos. write (buf, 0, len); 48} 49 OutputStream out = socket. getOutputStream (); // get the output stream of the server side 50 out. write ("uploaded successfully "). getBytes (); // After the upload is successful, write "uploaded successfully" 51 fos to the client. close (); // close the output stream object 52 socket. close (); // close Socket object 53} catch (Exception e) {54 throw new RuntimeException (e); 55} 56} 57}

Client Program:

1 import java. io. fileInputStream; 2 import java. io. inputStream; 3 import java. io. outputStream; 4 import java.net. inetAddress; 5 import java.net. socket; 6 7 public class Example8 {8 public static void main (String [] args) throws Exception {9 Socket socket = new Socket (InetAddress. getLocalHost (), 10001); // create a client Socket object and specify the IP address and port number 10 OutputStream out = socket. getOutputStream (); // get the Socket output stream object 11 // create Fil EInputStream object 12 FileInputStream FCM = new FileInputStream ("/Users/adims/Downloads/WechatIMG1.jpeg"); 13 byte [] buf = new byte [1024]; // define a byte array 14 int len; // define an int type variable len15 while (len = Fi. read (buf ))! =-1) {// read data cyclically 16 out. write (buf, 0, len); 17} 18 socket.ShutdownOutput (); // Disable the client output stream 19 InputStream in = socket. getInputStream (); // get the input stream object 20 byte [] bufMsg = new byte [1024]; // define a byte array 21 int num = in. read (bufMsg); // receives information from the server 22 String Msg = new String (bufMsg, 0, num); 23 System. out. println (Msg); 24 FCM. close (); // close the input stream object 25 socket. close (); // close Socket object 26} 27}

Note: The shutdownOutput () method is very important because the server-side program reads the data sent by the client in the while loop and ends the loop only when-1 is read, if the client does not call the shutdownOutput () method to close the output stream, the server will not read-1, but will always execute the while loop, and the client server will read (byte []) the method is also a blocking method, so that the client and the server enter a "deadlock" state.

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.