Network programming based on TCP protocol:
TCP/IP communication protocol is a reliable network protocol, he set up a socket at both ends of the communication, thereby forming a network virtual link between the two ends of the communication. Once the virtual network link is established, the programs at both ends can communicate through the virtual link. Java provides a good encapsulation of network traffic based on TCP protocol, Java uses the socket object to represent both ends of the communication interface, and through the socket generated IO stream for network communication.
(1) By using the IP protocol, the intenet becomes a network that allows the connection of different types of computers and different operating systems.
(2) IP protocol can only ensure that the computer can send and receive packet data. The IP protocol is responsible for transferring messages from one host to another, and the message is split into packets in the process of transmission.
(3) IP protocol can not solve the data packet in the transmission process may occur problems. To resolve problems that may occur, computers that are connected to the Internet also need to install a TCP protocol to provide reliable and undifferentiated communication services.
(4) The TCP protocol is called an end-to-end protocol. This is because it plays an important role in connecting the two computers-when a computer needs to be connected to another remote computer, the TCP protocol lets them establish a connection: a virtual link for sending and receiving data.
(5) The TCP protocol guarantees the accuracy of the data in the transmission. The TCP protocol uses the resend mechanism-when a communication entity sends a message to another communication entity, it needs to receive a confirmation message from another communication entity, and if no confirmation message is received from another communication entity, the message is sent again.
——————————————————————————————————————————————
To create a TCP server side using ServerSocket:
(1) A class in Java that accepts connection requests from other communication entities is the Serversocket,serversocket object used to listen for socket connections from the client, and it will remain connected if there is no connection. ServerSocket contains a method that listens for requests from client connections.
Socket accept () If a client socket connection request is received, the method returns a socket corresponding to the client's socket, otherwise the method will remain in the waiting state and the thread is blocked.
(2) To create the ServerSocket object, the ServerSocket class provides the following constructors:
ServerSocket (int port) creates a serversocket with the specified port ports. The port should have a valid port integer value, that is, 0–65535.
ServerSocket (int port, int backlog) adds a backlog to change the queue length
ServerSocket (int port,int backlog,inetaddress localaddr) when there are multiple IP addresses in the machine, Allows the LOCALADDR parameter to be specified to bind the ServerSocket to the specified IP address.
(3) When the ServerSocket is used, the close () method should be used to serversocket the ServerSocket. In general, the server should not only accept a client request, but should continue to accept requests from the client, so the Java program will often invoke the ServerSocket accept () method through loops:
Create a ServerSocket to listen for connection requests for client sockets
ServerSocket ss=new ServerSocket (30000); More than 1024 ports are usually recommended for use
Use loops to continuously accept requests from clients
while (true) {
Each time a socket request is received from the client, the server side also generates a socket
Socket s=ss.accept ();
The following can be used to communicate with the socket
}
————————————————————————————————
To communicate using a socket:
(1) The client can usually use the socket's constructor to connect to the specified server, and the socket usually has the following two constructors:
Socket (inetaddress/string remoteaddress, int port) creates a socket connected to a remote host, remote port, which does not specify a local address, a local port, and defaults to the default IP address of this computer. By default, the system dynamically allocated ports are used.
Socket (inetaddress/string remoteaddress, int port,inetaddress localaddr,int localport) creates a socket connected to a remote host, a remote port, and specifies the native address and native port, which is applicable to situations where the local host has multiple IP addresses.
A program typically uses a string object, such as 192.168.2.3, to specify a remote IP address. When the local host has only one IP address, it is simpler to use the first method, such as:
To create a socket connected to this computer, port 30000
Socket s =new socket ("127.0.0.1", 30000);
The following can be used to communicate with the socket
When the program executes the code above, the code connects to the specified server side, allowing the server-side Secversocket Accept () method to execute downward, and the server-side and the client produce a pair of connected sockets.
(2) When the server-side, the client generated the corresponding socket, the program no longer need to distinguish between the server and the client, but through their respective sockets for communication. The socket provides the following two methods to obtain the input and output streams:
InputStream getInputStream () returns the input stream corresponding to the socket object, allowing the program to fetch the data from the socket through the input stream.
OutputStream Getoutputstream () returns the output stream corresponding to the socket object, allowing the program to output data from the socket through the output stream.
Program Example: A Simple network communication program:
Server side: Set up server listening and use socket to get input output stream:
Import java.io.IOException;
Import Java.io.PrintStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;
public class Server {public
static void Main (string[] args) throws IOException {
//Create a ServerSocket, The connection request for listening to the client socket
serversocket ss=new serversocket (30000);
Use loops to continuously accept requests from clients
while (true) {
//whenever a request for a client socket is received, the server side also generates a socket
socket S =ss.accept () ;
The output stream corresponding to the socket is packaged into PrintStream
printstream ps=new printstream (S.getoutputstream ());
Ps.println ("Hello, Server Side received");
Turn off the output stream and close the socket
ps.close ();
S.close ();}}
Client: Use the socket to establish a connection with the specified IP address, specified port, and use the socket to get the input stream read data.
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.net.Socket;
Import java.net.UnknownHostException;
public class Client {public
static void Main (string[] args) throws ioexception{
socket socket=new socket (" 127.0.0.1 ", 30000);
Wraps the input stream corresponding to the socket into the corresponding BufferedReader
bufferedreader br=new bufferedreader (New InputStreamReader ( Socket.getinputstream ()));
Perform normal IO operation
String line =br.readline ();
SYSTEM.OUT.PRINTLN ("Data from the server:" +line);
Turn off the output stream and close the socket
br.close ();
Socket.close ();
}
(3) in the actual application, the program may not want to let straight network connection, read server data process has been blocked, but hope that the current network connection, read operation after a reasonable time, the system automatically thought that the operation failed, the reasonable time is super long. The socket object provides a setsotimeout (int timeout) method to set the timeout length.
Socket s=new socket ("127.0.0.1", 30000);
Set timeout after 10 seconds
S.setsotimeout (10000);