1. Entry-level client/server communication program written in Java

Source: Internet
Author: User

The viewpoint and example of this article are from the Java Network Programming excellent solution. The author is Sun weiqin, and the Publishing House is the Electronic Industry Publishing House.

Java Network programs all adopt the customer/server communication mode and are committed to implementing the application layer. The transport layer provides a Socket socket interface to the application layer. The socket encapsulates the data transmission details of the lower layer. The Application Layer Program uses Socket to establish a connection with the remote host and transmit data.

 

From the application layer perspective, a communication process between two processes starts from establishing a connection, and then exchanges data to the end of the disconnection. A socket can be seen as a receiver at both ends of a communication line. A process uses a socket to send and receive data.

For example, process A1 ------- socket <------ TCP connection -----> socket ------- process B1

 

In Java, there are three socket classes: java.net. socket, java.net. serversocket, and datagramsocket. The socket and serversocket classes are based on the TCP protocol, and the initramsocket class is based on the UDP protocol.

 

  • Create echoclient

Package com. sockettest;

Import java. Io. bufferedreader;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. inputstreamreader;
Import java. Io. outputstream;
Import java. Io. printwriter;
Import java.net. Socket;

Public class echoclient {
Private string host = "localhost"; // name of the host where the echoserver process is located. "localhost" indicates echoclient and echoserve.
// The process runs on the same host.
Private int Port = 8000; // port on which the echoserver process listens
Private Socket socket;
 
Public echoclient () throws ioexception {
If (socket = NULL ){
Socket = new socket (host, Port); // If the socket object is successfully created, the connection between echoclient and echoserver is established.
System. Out. println ("connect to the server! ");
}
}
 
Private printwriter getwriter (Socket socket) throws ioexception {
Outputstream socketout = socket. getoutputstream ();
Return new printwriter (socketout, true );
}
 
Private bufferedreader getreader (Socket socket) throws ioexception {
Inputstream socketin = socket. getinputstream ();
Return new bufferedreader (New inputstreamreader (socketin ));
}
 
/**
* The Most Important Method in the echoclient class. This method constantly reads the string that the user inputs from the console, sends it to the echoserver, and then sends the echoserver
* Print the returned string to the console. If the string entered by the user is "bye", the communication with the echoserver will end, and the socket. Close () method will be called to disconnect.
* Connection.
*/
Public void talk (){
Try {
// After establishing a connection between echoclient and echoserver, echoclient obtains the output stream and input stream from the socket object, and can exchange data with echoserver.
Bufferedreader BR = getreader (socket );
Printwriter PW = getwriter (socket );

Bufferedreader localreader = new bufferedreader (New inputstreamreader (system. In ));

String MSG = NULL;
While (MSG = localreader. Readline ())! = NULL ){
PW. println (MSG); // output information to the server
System. Out. println (Br. Readline (); // print information accepted by the slave server

If (msg. Equals ("bye") // if the message sent by the customer is "bye", the communication ends.
Break;
}


} Catch (ioexception e ){
E. printstacktrace ();
} Finally {
Try {
If (socket! = NULL) socket. Close (); // disconnect
} Catch (ioexception e) {e. printstacktrace ();}
}
}
 
 
Public static void main (string ARGs []) throws ioexception {
New echoclient (). Talk ();
}
}

 

 

  • Create an echoserver

Package com. sockettest;

Import java. Io. bufferedreader;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. inputstreamreader;
Import java. Io. outputstream;
Import java. Io. printwriter;
Import java.net. serversocket;
Import java.net. Socket;

Public class echoserver {

Private int Port = 8000;
Private serversocket;
 
Public echoserver () throws ioexception {
If (serversocket = NULL ){
// The server program receives connection requests from the client program by listening to the port. In the server program, you must first create a serversocket object,
// Specify the listening port in the constructor.
// The serversocket constructor registers the current process as a server process in the operating system.
Serversocket = new serversocket (port); // listen to port 8000
System. Out. println ("server startup! ");
}
}
 
Public String echo (string MSG ){
Return "Echo:" + MSG;
}
 
// The socket class provides the getoutputstream () method to return the output stream outputsteam object. The program can send data to the other party by writing data to the output stream,
// The output stream of the socket can be decorated by filtering and leaving. In this method, the output stream is obtained first, and then decorated with printwriter.
// The println () method can write a row of data.
Private printwriter getwriter (Socket socket) throws ioexception {
Outputstream socketout = socket. getoutputstream ();
Return new printwriter (socketout, true); // The parameter true indicates that the printwriter cache automatically overflows and writes data to the destination.
}
 
// The socket class provides the getinputstream () method to return the inputstream object of the input stream. The program only needs to read data from the input stream to receive data from the other party,
// The input stream of the socket can also be decorated with a filter stream. In this method, the input stream is obtained first and then decorated with bufferedreader.
// The Readline () method can read a row of data.
Private bufferedreader getreader (Socket socket) throws ioexception {
Inputstream socketin = socket. getinputstream ();
Return new bufferedreader (New inputstreamreader (socketin ));
}
 
/**
* The most important method of the echoserver class, which constantly waits for the client's connection request. When the serversocket. Accept () method returns a socket object,
* This means that a connection is established with a customer. Next, the output stream and input stream are obtained from the socket object, and printwriter and bufferedreader are used respectively.
* To describe them. Then, call bufferedreader's Readline () method to read the string XXX from the customer, and then call printwriter's
* The println () method returns the string ECHO: XXX to the customer. When the string sent by the customer is "bye", the communication with the customer ends,
* Call socket. Close () to disconnect.
* Ps. This method cannot communicate with multiple customers at the same time. When the echoserver receives a connection from a customer, it communicates with the customer. After the communication is completed, the connection is disconnected and then
* Receives the next client connection. If multiple clients request connections at the same time, these customers must queue for the echoserver response.
*/
Public void Service (){
While (true ){
Socket socket = NULL;
Try {
// The server program calls the serversocket object's accept () method. This method keeps listening to the port and waits for the client's connection request.
// For the connection request, the accept () method returns a socket object, which forms a communication line with the client's scoket object.
Socket = serversocket. Accept (); // wait for the client to connect

// The socket object contains the customer's address and port
System. Out. println ("New Connection accepted"
+ Socket. getinetaddress () + ":" + socket. getport ());

Bufferedreader BR = getreader (socket );
Printwriter PW = getwriter (socket );

String MSG = NULL;
While (MSG = Br. Readline ())! = NULL ){
System. Out. println (MSG); // print the accepted information
PW. println (echo (MSG); // output information to the client
If (msg. Equals ("bye") // if the message sent by the client is "bye", the communication ends.
Break;
}

} Catch (ioexception e ){
E. printstacktrace ();
} Finally {
Try {
If (socket! = NULL) socket. Close (); // disconnect
} Catch (ioexception e ){
E. printstacktrace ();}
}
}
}
 
 
 
Public static void main (string [] ARGs) throws ioexception {
// Todo auto-generated method stub
New echoserver (). Service ();
}

}

 

 

Run echoserver first, then echoclient, and enter a string in the echoclient console. When the input string is bye, communication with echoserver ends.

Related Article

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.