Java Network Programming (1)-a simple server/client application

Source: Internet
Author: User

In Java, we use java.net. socket and its related classes to complete network-related functions. The socket class is very easy to use, Because Java technology hides the complex process of establishing a network connection and sending data through a connection. The following content applies only to the TCP protocol.

1. Connect to the server

We can use the constructor of the socket class to open a socket, such

 
Socket Sk = new socket ("210.0.235.14", 13 );

Here, 210.0.235.14 is a string object in decimal notation, indicating the IP address (or host name) of the target host, and 13 indicating the Port 13 of the target host. 210.0.235.14 is a Time Service server located in Hong Kong. The default port number of the Time Service server is usually 13.

Note: Before successfully connecting to the server,ProgramWill be blocked.

Next we can use the getinputstream () method of the socket class to obtain an inputstream object. Through this object, we can obtain the information sent to us by the target host:

 
Inputstream instream = Sk. getinputstream ();

Similarly, to send data to the target host, you can call the getoutputstream () method to obtain an output stream object.

The following example connects to the Time Service server and prints the returned information to the standard output:

Try {socket Sk = new socket ("210.0.235.14", 13); SK. setsotimeout (3000); inputstream instream = Sk. getinputstream (); // get the input stream object scanner SC = new streams (instream); // print the data to the console while (SC. hasnextline () {string STR = SC. nextline (); system. out. println ("output:" + Str);} SK. close ();} catch (sockettimeoutexception e) // timeout exception {system. out. println ("time out! ");} Catch (exception e) {e. printstacktrace ();}

CodeThe setsotimeout () method can be used to set the timeout time. If the read/write operation is not completed after the specified time, sockettimeoutexception is thrown. You can capture this exception to close the connection.

Another timeout problem must be solved. It is the constructor of the socket class.

New socket (host, Port );

It will be blocked infinitely until the connection to the target host is established successfully. This is certainly not what we want. We can solve this problem by calling the following method:

 
Socket Sk = new socker (); SK. Connect (New inetsocketaddress (host, port), 2000); // set the timeout value to 2 seconds.

2. Obtain the host address

The static method getbyname (hostname) of the inetaddress class can return the inetaddress object representing a host address. This object is closed with a 4-byte sequence, that is, the Host IP address. Then call the gethostaddress () method to return a String object that represents the IP address.

Host names with a large access volume usually correspond to multiple IP addresses for load balancing. We can call the getallbyname () method to obtain all host addresses. This method returns an array of inetaddress objects.

The following is a simple applet. The function is to print the local IP address if the parameter is not set in the command line. If the host name is specified, print all IP addresses of the Host:

 
Package CLS; import java.net. *; public class showip {public static void main (string [] ARGs) {try {If (ARGs. length> 0) {string hostname = ARGs [0]; // host name inetaddress [] ADDR = inetaddress. getallbyname (hostname); // obtain all the addresses of the host // print the output to the console for (inetaddress address: ADDR) {system. out. println (address. gethostaddress () ;}} else {system. out. println (inetaddress. getlocalhost (). gethostaddress () ;}} catch (exception e) {e. printstacktrace ();}}}

Iii. server programs

Server applications use the serversocket class to create sockets and bind them to local ports, as shown in figure

Serversocket sock = new serversocker (8000 );

The sock. Accept () method keeps the program waiting for connection. This method returns a socket object representing the new connection only when a client is connected, that is, the method will be blocked.

Here, we generally need to enable a new thread for each connection.

The following is a complete example. The server waits for a connection at Port 8400. Every time a connection is established, a new thread starts to serve it and writes 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 servsocket = new serversocket (8400); int amount = 0; while (true) {Socket Client = servsocket. accept (); ++ amount; Date time = new date (); string prompt = time. tostring () + ":" + amount +" User "+ client. getinetaddress (). gethostaddress () + "connected \ n"; system. out. print (prompt); // output the serverdemo information on the console. writelog (prompt); // write to the file // start a new threadthread th = new thread (New servthread (client, amount); th. start () ;}} catch (exception e) {e. printstacktrace () ;}/// write the log file public static void writelog (string Str) {file logfile = new file ("server-log.txt "); try {filewriter out = new filewriter (logfile, true ); Out. append (STR); out. close ();} catch (exception e) {e. printstacktrace () ;}}/ ** service Thread class */class servthread implements runnable {private Socket Client; private int IX; Public servthread (socket SOC, int IX) {client = SOC; this. IX = IX;} public void run () {try {inputstream instream = client. getinputstream (); outputstream outstream = client. getoutputstream (); Response Recv = new response (instream); printwriter send = new Printwriter (outstream, true); send. println ("Welcome ~ Just a few words! [Enter 'bye' to close the connection] "); While (Recv. hasnextline () {string STR = Recv. nextline (); If (Str. equals ("bye") {send. println ("see you later ~ ^-^ "); Break;} Send. println ("this is a test program, and there is no function yet");} date time = new date (); string prompt = time. tostring () + ":" + ix + "user" + client. getinetaddress (). gethostaddress () + "disconnected \ n"; system. out. print (prompt); serverdemo. writelog (prompt); // write it to the client in the file. close ();} catch (exception e) {e. printstacktrace ();}}}

This program has been stored on the server. You can use the Telnet youthol. TK 8400 command to experience the running results of this program ..

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.