The example of this article describes the simple service client application of Java network programming. Share it for everyone for your reference. The specifics are as follows:
In Java, we use Java.net.socket and its related classes to complete related functions related to the network. The socket class is very easy to use, because Java technology hides the complex process of establishing network connections and sending data through connection. The content mentioned below is only applicable to the TCP protocol.
1. Connect to the server
We can use the constructor of the socket class to open a socket, such as
Socket sk = new socket ("210.0.235.14", 13);
Among them, 210.0.235.14 is a string object with a tip of advancement, which indicates the IP address (or host name) of the host's host, and 13 indicates the designated port 13 of the connected target host. The 210.0.235.14 here is a timing server located in Hong Kong. The default port of the time server is generally 13.
Note that the program will block before successfully connecting to the server.
Next, you can use the GetInputStream () method of the socket class to get an inputStream object. Through this object, you can get the information sent by the target host to us:
InputStream Instream = SK.GetinputStream ();
In the same way, to send data to the target host, you can call the getoutPutStream () method to get an output stream object.
The following example function is to connect the timing server, and print the returned information into the standard output:
Try {socket sk = New Socket Canner (Instream); // Print the data to the console While (sc.hasnextline ()) {string str = sc.nextline (); System.out.println ("Output:" + Str);} SK.Close ();} xception E ) // Time -time abnormality {System.out.println ("Time Out!");} Catch (Exception E) {e.printstacktrace ();}
The setsotimeout () method in the code can set the timeout, that is, if the setting time is not completed, the read and write operation is not completed, and the sockettimeoutexception will be thrown out to close the connection by capturing this abnormality.
In addition, there is a timeout problem that must be solved, that is, the constructor of this socket class
new socket (host, port);
It will always block infinitely until the connection of the target host was successfully established. This is of course not what we want. We can solve this problem by calling below:
Socket sk = new socker (); SK.Connect
2. Get the host address
The static method of the INETADDRSS class GetByname (hostname) can return the INETADDRESS object that represents a host address. This object is closed with a 4 -byte sequence, that is, the IP address of the host. Then call the gethostaddress () method to return a String object that indicates the IP address.
Some large visits are usually corresponding to multiple IP addresses to achieve load balancing. We can call the getallByname () method to get all the host address, which returns an array of an INetaddress object.
The following is a simple mini -program. The function of implementing is that if the parameters are not set in the command line, the local IP address is printed. If the host name is specified, all the IP address of the host is printed:
Package CLS; Import Java.net.*; Public Class Showip {Public Static Void Main (String [] ARGS) {try {if (ARGS.Length> 0) {String HostName = ARGS [ 0]; // The host name INetaddress [ ] Addr = InetadDress.getallByname (hostname); // get all the address of the host // Print to the console for (INETADDRSS Address: Addr) {System.out.println ();}} else { System.out.println (Inetaddress.getLocalHost (). GetHostaddress ());}} Catch (Exception E) {e.printstacktrace ();}}}}}}}}}}}}}}}}}}}}}}}
3. Server program
The server application uses the Serversocket class to create a socket, and it is bound to the local port, such as
Serversocket Sock = New Serversocker (8000);
Sock.Accept () method allows the program to keep waiting for connection. This method returns a socket object that represents the new connection only when a client is connected, that is, this method will block.
Here is generally to open a new thread for each connection to serve it.
Below is a complete example. The server is waiting for connection at the 8400 port. Whenever connection is connected, a new thread serves it and puts the connection information to the log file:
Package CLS; Import Java.io.*; Import Java.net.*; Import Java.util.*; Public Class Serverdemo { / ***@param ARGS* / Public Static Void main (String [] args) {try { // Serversocket ServSocket = New Serversocket (8000); Serversocket Service = New Serversocket (8400); int amount = 0; While (TRUE) {socket client = s Ervsocket.Accept (); ++ amount; date time = new date () ; String prompt = time.tostring () + ":" + amount + "user" + client.getinetadress (). Gethostaddress () + "has been connected/n"; Outputting information serverDemo.writelog (prompt); // write to the file // start a new thread thread th = new thread (new service (client, amount)); th.start ();} catch ( Exception E) {e.printstacktrace ();} // Write into the log file Public Static Void Writlog (String Str) {File Logfile = New File ("Server-Log.txt"); try {filewrit Er Out = New Filewriter ( logfile, true); out.append (str); out.close ();} Catch (Exception E) {e.printstacktrace ();} /** service thread class* / class services Able {Private Socket Client ; Private Int ie; Public Servthread (Socket Soc, IX) {Client = SOC; This.ix = ie; putstream (); outputStream outstream = Client.getputstream ( );; Printwriter Send = New Printwriter (Outstream, TRUE); Send.println ("Welcome to talk a few words! [Enter the 'bye' off the connection] "); about (rest.hasnextline ()) {string str = recv.nextline (); if (stra.equals (" bye ") {send.println (" see you later ~ ^-^"); Break;} Send.println (" This is a test program, there is no function now "); + IX + "User" + Client.getinetaddress (). Gethostaddress () + "has been disconnected to connect/n"; System.out.print (Prompt); serverDemo.writelog (prompt); // Write into the file client.close ();} Catch (Exception E) {e.printstacktrace ();}}}
This program has been placed on the server, you can use Telnet Youthol.tk 8400 command to experience the running results of this program
It is hoped that this article is helpful to everyone's Java program design.