1. Overview
The Socket class is the basic class for Java to perform client TCP operations. This class itself uses code to communicate through the local TCP stack of the host operating system. The Socket class methods will establish and destroy connections and set various Socket options.
The ServerSocket class is the basic class for Java to perform server-side operations. This class runs on the server and listens for inbound TCP connections. Each socket server listens for a port of the server. When the client of the remote host tries to connect to this port, the server is waked up and returns a normal socket object representing the socket between the two hosts.
2. What is TCP?
TCP is a connection-oriented, reliable, byte stream-based transport layer communication protocol. TCP communication is divided into client and server, and the corresponding objects are Socket and ServerSocket respectively.
When a computer needs to connect to another remote computer, the TCP protocol allows them to establish a connection: a virtual link for sending and receiving data. The TCP protocol is responsible for collecting information packets and sending them in appropriate order, and then reverting them correctly after receiving them at the receiving end. In order to ensure that the data packet is accurate during transmission, TCP uses a retransmission mechanism: when a communication entity sends a message to another communication entity, it needs to receive another entity's confirmation information. If no confirmation information is received, the information sent just now will be resented again.
III. TCP communication
1. Constructor
The Socket class implements client sockets, and the constructor can specify the host and port you want to connect to. The host can be specified as InetAddress or String, and the port is always specified as an int value between 0 and 65535.
Socket s=new Socket("127.0.0.1", 10001);//Create a stream socket and connect it to the specified port number on the specified hostServerSocket class implements server sockets. The server socket waits for the request to be passed in through the network, it performs some operations based on the request and then returns the result to the requester.
ServerSocket ss=new ServerSocket(10001);//Create a server socket bound to a specific port
2. Example: TCP file copying
Client:
public class ClientDemo{public static void main(String[] args) throws UnknownHostException, IOException {Socket s=new Socket("127.0.0.1", 10004);BufferedReader buf = new BufferedReader(new FileReader("C://Users//Administrator//Desktop//1.txt"));String line=null;/*PrintWriter out=new PrintWriter(s.getOutputStream(),true); while((line=buf.readLine())!=null) { out.println(line); } */BufferedWriter out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); while((line=buf.readLine())!=null) {out.write(line);out.newLine();out.flush();}s.shutdownOutput();BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));String str=in.readLine();System.out.println(str);s.close();buf.close();}}Server side:
public class ServerDemo{public static void main(String[] args) throws IOException {ServerSocket ss=new ServerSocket(10004);Socket s=ss.accept();BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));String line=null;/*PrintWriter buf=new PrintWriter(new FileWriter("C://Users//Administrator//Desktop//2.txt"),true); while((line=in.readLine())!=null) { buf.println(line); }*/BufferedWriter buf=new BufferedWriter(new FileWriter("C://Users//Administrator//Desktop//2.txt"));while((line=in.readLine())!=null) {buf.write(line);buf.newLine();buf.flush();}PrintWriter out=new PrintWriter(s.getOutputStream(),true);out.println("Transfer successful!");ss.close();buf.close();}}4. Socket's application on browsing
We can write the server side in Eclipse and then access it using the browser.
eg, server-side code is:
public class SocketServer{ public static void main(String[] args) throws IOException { ServerSocket server=new ServerSocket(11000); Socket client=server.accept(); PrintWriter out=new PrintWriter(client.getOutputStream(),true); out.println("Hello!"); server.close(); }}Then open IE browser, enter http://192.168.1.120:11000/ in the address (192.168.1.120 is the local IP address), and the result is
In normal applications, the browser issues a request to the Tomacat server to obtain resources such as web page images. Tomca is a server-side software written in Java.
Now we write the server side as:
public class SocketServer{ public static void main(String[] args) throws IOException { ServerSocket server=new ServerSocket(11000); Socket client=server.accept(); PrintWriter out=new PrintWriter(client.getOutputStream(),true); BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream())); String line=null; while((line=in.readLine())!=null) System.out.println(line); out.println("Hello!"); server.close(); }}Then, when accessing with the browser, you can see that the request header data sent by the browser (client) to the server is:
Using the above principles, we can write browser-side (client) software similar to IE by ourselves. First add a demo.html resource to Tomcat's installation directory C:/apache-tomcat-7.0.62/webapps/myweb, and then write the client, the code is as follows:
public class ClientDemo{public static void main(String[] args) throws UnknownHostException, IOException {Socket s=new Socket("192.168.1.120",8080);PrintWriter out=new PrintWriter(s.getOutputStream(),true);//Send the request to the server out.println("GET /myweb/demo.html HTTP/1.1");out.println("Accept:*/*");out.println("Host: 192.168.1.120:11000");out.println("Connection: Keep-Alive");//Output empty lines, this step is indispensable out.println();BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));String line=null;//Return the server's response file while((line=in.readLine())!=null) {System.out.println(line);}s.close();}}Next, start Tomcat. That is, double-click the startup.bat file in C:/apache-tomcat-7.0.62/bin. Then run the above client code, and you can see the response data returned by Tomacat:
Summarize
The above is the complete code example of TCP communication in this article about Java network programming, and I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
The Basics of Java Network Programming: One-way Communication
Sample code for implementing socket communication in Java multithreaded programming
Detailed explanation of the code of thread communication producer consumer model and waiting wake-up mechanism of Java multi-threaded
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!