Java is a language that can be used for network programming, and it provides two powerful network support mechanisms: URLs that access network resources and classes that communicate with sockets to meet different requirements. One is the use of URLs to access Internet resources, the other is for the application of Client/server (client/server) mode and the implementation of some special protocols, its communication process is based on the TCP/IP protocol Transmission layer Interface socket implementation. This article wants to briefly introduce the Java implementation method of socket programming.
Most of the communication components that customers use between servers are based on socket interfaces. The socket is a network communication endpoint between two programs for two-way data transmission, with an address and a port number to identify. Each service program is serviced in a single port, and the client who wants to use the service must also connect to that port. Socket because it is based on the transport layer, so it is relatively primitive communication protocol mechanism. Through the data representation of the socket is the word throttling information, so the communication between the two sides to complete a specific application must be in accordance with the way the two parties agreed to format and explain the data, we can see that the use of socket programming is more cumbersome, but it has more flexibility and a wider use of the field.
Some friends ask, what is the pattern of client/server work? OK, now I'd like to combine a picture to describe their working mode.
So how does a Java application implement the above process? The java.net package has two classes of sockets and ServerSocket, which are used to create socket traffic on both the client and server. Let's take a look at the process written by the client segment:
1, first call the socket class constructor, with the server's specified IP address or the specified host name and the specified port number as parameters, create a socket stream, in the creation of the socket stream contains the request to the server to establish a communication connection process implementation.
2, established the client communication socket after. You can use the method getInputStream () and Getoutputstream () of the socket to create an input/output stream. In this way, after using the socket class, the network input output is also transformed into the process of using the Stream object.
3. Read and write throttling data using the corresponding method of the input output stream object, because the socket,socket used for the communication is the endpoint that establishes the connection with the server, so the data will be obtained from the server or sent to the server via the connection. At this time we can to the byte stream data according to the agreement between the client and server processing, complete the communication task between the two parties.
4. After the communication task is completed, we use the close () method of the stream object to turn off the input and output stream for network communication, and close the socket with the closed () method of the socket object.
Below, I want to use a simple example to further explain the client program writing
Code One:
Import java.io.*;
Import java.net.*;
public class Socketcommunicationclient
{
public static void Main (string[] args)
{
try{
Socket clientsocket =new socket ("mice", 9000);//Create a stream Socket and connect to port 9000 on the host mice
OutputStream output Stream =clientsocket.getoutputstream ()//write byte to this socket
DataInputStream input=new DataInputStream (Clientsocket.getinputstream ());
FILE://creates a new data input stream to read data from a specified input stream
int C;
String response; See, this is the dead loop where the client listens for user input all the time. while ((c= System.in.read ())!=-1)//takes the input string from the screen and decomposes it into characters
{
Output.write ((byte) c);
if (c== '/n ')//If the character is carriage return, the output string buffer
{
Output.flush ();
Response=input.readline ();
SYSTEM.OUT.PRINTLN ("Communication:" +response);
}
}
Output.close ();
Input.close ();
Clientsocket.close ();
catch (Exception e) {
System.err.println ("Exception:" +e);
}
}
}
This program is a very simple example of data communication, the program first creates a socket and connects to port 9000 on the host mice, then opens the input output stream, and the program receives characters from the standard input and writes to the stream, each full line (marked by the user typing the carriage return), The string in the buffer is sent to the server-side program on the mice for processing, waiting for the server-side response. The Input.readline () method call will cause the program to stall until an answer is received, and the program will repeat the process until the user enters the abort character. The final program to close the socket input output stream, in the closed socket and server-side connection. Above we saw how to use Java to write the client socket interface program, I would like to briefly talk about the server-side socket Interface Program Java implementation method, the process is as follows:
1, first call the ServerSocket class to a port number as a parameter, create a ServerSocket object, that is, server-side service program on the specified port listening to the socket.
2, the server-side program uses the ServerSocket object's accept () method, receives the connection request from the client program, at this time the server side will remain stagnant until receives the client to send the connection request, this method will return a new socket class instance, Represents a communication link that is established with the client in the service program's communication endpoint. If you are using Java multithreaded programming, you can implement concurrent servers and continue to listen for connection requests from other customers.
3, use the new socket object to create input, output stream objects.
4, using the method of streaming object and the data transmission of the client, identify and process the request data from the client according to the agreed Protocol, and return the processing result to the client.
5. After the client has finished working, the server-side program shuts down the stream and the communication socket of the client communication.
6. Between the end of the server program, you should close the socket used for listening.
Let's look at the Java implementation of a server-side program:
Code two:
Import java.net.*;
Import java.io.*;
public class Socketcommunicationserver
{
public static void Main (string[] args)
Try
{
Boolean flag=true;//set flag bit to True
Socket client=null;//creates a socket client to receive requests from the client
String Inputline;
ServerSocket serversocket =new ServerSocket (9000);//Create a server socket with Port 9000
SYSTEM.OUT.PRINTLN ("Server listens on port 9000");
FILE://can also use Serversocket.getlocalport () to get the port number
while (flag)
{
Client=serversocket.accept ();
FILE://listens and accepts a connection to this socket, blocking the method until a connection is generated
DataInputStream input=new DataInputStream (New Bufferedinputstream (Client.getinputstream ()));
PrintStream output=new PrintStream (New Bufferedoutputstream (Client.getoutputstream ());
while ((Inputline= input.readline ())!=null)
{
if (Inputline.equals ("Stop"))
{
Flag=false;
Break
}
Output.println (Inputline);
Output.flush ();
}
Output.close ();
Input.close ();
Client.close ();
}
Serversocket.close ();
}catch (IOException e) {}
}
}
} ---------------------------------------------------------------------------------------- Here simple to say how to achieve similar to QQ chat that kind of function, in fact Tencent QQ is based on UDP, rather than TCP, we are here purely to cover up this interaction, so, first use the next bar. Client: The client has read, has written. The realization of the read operation is to read the data through the getInputStream method in an infinite loop or a method called once every few minutes. Write operation, is the same, there is a cycle, has been listening to the input of our clients, monitor the content to send data to the server. Service side: In addition to reading and writing similar to the client, there is a multiple client problem, the problem is very simple, we can start a corresponding thread for each client. |