Overview of network programming
Network programming refers to writing programs running on multiple devices (computers), all connected through the network.
The J2SE API in the package contains classes and interfaces, which provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without paying attention to communication details.
Support for two common network protocols is provided in the package:
TCP: TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte stream-based transmission layer communication protocol. The TCP layer is an intermediate layer located above the IP layer and below the application layer. TCP guarantees reliable communication between two applications. Usually used in the Internet protocol, it is called TCP/IP.
UDP: UDP (English: User Datagram Protocol, User Datagram Protocol), located in the transport layer of the OSI model. A connectionless protocol. Provides datagrams to send data between applications. Because UDP lacks reliability and belongs to a connectionless protocol, applications usually have to allow some missing, wrong or duplicate packets.
kind
This class represents an Internet Protocol (IP) address. The following demonstrates the more useful methods when programming Socket:
import ; import ; /** * InetAddress class demonstration */ public class InetAddressTest { public static void main(String[] args) throws UnknownHostException { // Get the InetAddress object of the machine: Host name + IP address InetAddress localHost = (); (localHost); // Get InetAddress object according to host name InetAddress host1 = ("Dahe-Windows11"); (host1); // Get InetAddress object according to the domain name InetAddress host2 = (""); (host2); // Get the corresponding address through the InetAddress object String hostAddress = (); (hostAddress); // Get the host name or domain name through the InetAddress object String hostName = (); (hostName); } }
Output:
XXX-WindowsXX/192.168.0.1
XXX-WindowsXX/192.168.0.1
/39.156.66.18
39.156.66.18
programming
Sockets use TCP to provide a communication mechanism between two computers. The client program creates a socket and tries to connect to the server's socket.
When the connection is established, the server creates a Socket object. Clients and servers can now communicate by writing and reading Socket objects.
Classes represent a socket, and classes provide server programs with a mechanism to listen to clients and establish connections with them.
The following steps appear when using sockets to establish a TCP connection between two computers:
- The server instantiates a ServerSocket object, indicating communication through a port on the server.
- The server calls the accept() method of the ServerSocket class, which will wait until the client connects to the given port on the server.
- While the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.
- The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, a Socket object is created on the client to communicate with the server.
- On the server side, the accept() method returns a new socket reference on the server that connects to the client's socket.
After the connection is established, by using I/O streams to communicate, each socket has an output stream and an input stream, the client's output stream is connected to the input stream on the server side, and the client's input stream is connected to the output stream on the server side.
TCP is a two-way communication protocol, so data can be sent at the same time through two data streams.
programming
TCP Byte Stream Programming
Let's simulate the process of communication between a server and a client:
Server:
import ; import ; import ; import ; /** * Server side */ public class SocketServer { public static void main(String[] args) throws IOException { // Listen on the local port 9999 // Details: You need to ensure that port 9999 is idle ServerSocket serverSocket = new ServerSocket(9999); // When there is no client link, it will block and wait for the link // If there is a client link, a Socket object will be returned Socket socket = (); // Get the data sent by the client through the input stream InputStream inputStream = (); // Read content byte[] buf = new byte[1024]; int readLne = 0; while ((readLne = (buf)) != -1) { (new String(buf, 0, readLne)); } // Close the resource (); (); (); } }
Client:
import ; import ; import ; import ; /** * Client */ public class SocketClient { public static void main(String[] args) throws IOException { // Link to the server, since it is a test program, you can directly obtain the address of the machine // Link to the 9999 port of the machine, and the link will return a Socket object after successful linking. Socket socket = new Socket((), 9999); // Create flow to send data to the server OutputStream outputStream = (); ("Hello Server".getBytes()); // Close the output stream object and socket (); (); ("Client Exit!"); } }
Run the server and the client at the same time. In this sample code, the client will send a streaming message to the server: Hello Server
Next, let's take a look at a more complex example: implementing dual communication between client and server
Server:
import ; import ; import ; import ; import ; /** * Server side */ public class SocketServer { public static void main(String[] args) throws IOException { // Listen on the local port 9999 // Details: You need to ensure that port 9999 is idle ServerSocket serverSocket = new ServerSocket(9999); // When there is no client link, it will block and wait for the link // If there is a client link, a Socket object will be returned Socket socket = (); // Get the data sent by the client through the input stream InputStream inputStream = (); // Read content byte[] buf = new byte[1024]; int readLne = 0; while ((readLne = (buf)) != -1) { (new String(buf, 0, readLne)); } // Send back a message to the client OutputStream outputStream = (); ("hello,client".getBytes()); // Set the end mark (); // Close the resource (); (); (); (); } }
Client:
import ; import ; import ; import ; import ; /** * Client */ public class SocketClient { public static void main(String[] args) throws IOException { // Link to the server, since it is a test program, you can directly obtain the address of the machine // Link to the 9999 port of the machine, and the link will return a Socket object after successful linking. Socket socket = new Socket((), 9999); // Create flow to send data to the server OutputStream outputStream = (); ("Hello Server".getBytes()); // Set the end mark (); // Get the server's loopback data InputStream inputStream = (); byte[] buf = new byte[1024]; int readLen = 0; while ((readLen = (buf)) != -1) { (new String(buf, 0, readLen)); } // Close the output stream object and socket (); (); ("Client Exit!"); } }
Note: The end mark needs to be set for a dual-ended communication, otherwise you will wait for each other and fall into a stalemate.
TCP character flow programming
Character flow programming requires the use of converting flow technology
Directly upload the code:
Client:
import .*; import ; import ; /** * TCP programming based on character streams * Client */ public class CharacterSocketClient { public static void main(String[] args) throws IOException { // Link to the server, since it is a test program, you can directly obtain the address of the machine // Link to the 9999 port of the machine, and the link will return a Socket object after successful linking. Socket socket = new Socket((), 9999); // Create flow to send data to the server OutputStream outputStream = (); // Use IO to convert streams BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream)); ("hello,server character stream"); // Insert a newline character to indicate the end of the written content (); // Use character streams and must be refreshed manually, otherwise the data will not be written to the channel (); // Set the end mark (); // Get the server's loopback data InputStream inputStream = (); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String s = (); (s); // Close the output stream object and socket (); (); (); (); ("Client Exit!"); } }
Server:
import .*; import ; import ; /** * TCP programming based on character streams * Server side */ public class CharacterSocketServer { public static void main(String[] args) throws IOException { // Listen on the local port 9999 // Details: You need to ensure that port 9999 is idle ServerSocket serverSocket = new ServerSocket(9999); // When there is no client link, it will block and wait for the link // If there is a client link, a Socket object will be returned Socket socket = (); // Get the data sent by the client through the input stream InputStream inputStream = (); // IO conversion stream BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); // You must use readLine to read String s = (); (s); // Send back a message to the client OutputStream outputStream = (); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream)); ("Hello,Client character stream"); (); (); // Close the resource (); (); (); (); (); (); } }
5. Upload files on the Internet
Server code:
import ; import ; import ; import ; import ; /** * File upload, server */ public class TCPFileUploadServer { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(8888); Socket socket = (); BufferedInputStream bis = new BufferedInputStream(()); byte[] bytes = (bis); String destFilePath = "networkprogramming\\tcp\\"; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath)); (bytes); (); // Close the resource (); (); (); } }
Client code:
import ; import ; import ; import ; import ; /** * File upload, client */ public class TCPFileUploadClient { public static void main(String[] args) throws Exception { Socket socket = new Socket((), 8888); // Create an input stream to read disk files String filePath = "D:\\"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath)); // The bytes at this time is the byte content of the file byte[] bytes = (bis); // Get the output stream through socket and send the bytes data to the server BufferedOutputStream bos = new BufferedOutputStream(()); (bytes); (); // Write data end mark (); // Close the resource (); (); } }
File download
Client code:
import .*; import ; import ; import ; /** * TCP file download client */ public class TCPFileDownloadClient { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(); ("Please enter the download file name:"); String downloadFileName = (); Socket socket = new Socket((), 9999); OutputStream outputStream = (); (()); // Set the write end flag (); // Accept the file byte array returned by the server BufferedInputStream bis = new BufferedInputStream(()); byte[] bytes = (bis); // Write files to disk String filePath = "D:\\" + downloadFileName + ".jpg"; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); (bytes); (); (); (); (); } }
Server code:
import ; import ; import ; import ; import ; import ; /** * TCP file download server */ public class TCPFileDownloadServer { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(9999); Socket socket = (); // Read the file name to be downloaded sent by the client InputStream inputStream = (); byte[] b = new byte[1024]; int len = 0; // The file name to be downloaded by the client String downloadFileName = ""; while ((len = (b)) != -1) { downloadFileName += new String(b, 0, len); } // The actual file name provided to the client to download String resFileName = ""; if ("color".equals(downloadFileName)) { resFileName = "networkprogramming\\tcp\\"; } else { resFileName = "networkprogramming\\tcp\\"; } BufferedInputStream bis = new BufferedInputStream(new FileInputStream(resFileName)); // Use tool class to save the file to an byte array byte[] bytes = (bis); BufferedOutputStream bos = new BufferedOutputStream(()); // Write to the data channel and return to the client (bytes); (); (); (); (); } }
The above is a detailed article that will help you learn Java network programming. For more information about Java network programming, please pay attention to my other related articles!