How to implement simple server/client echo using Java

Source: Internet
Author: User

Socket refers to the end point of the inter-process communication link in a specific programming model. Because of the popularity of this particular programming model, the Socket name has been reused in other fields, including Java technology.

To establish a connection, one machine must run a process to wait for the connection, and the other machine must try to reach the first machine. This telephone system is similar: one party must initiate a call, and the other party must wait for the call.

Java Network Model Diagram

The following describes how to write network applications using the java.net package on a server and client with the "Echo" function.

 

The main function of this example is to wait for the client's input, display the read information back to the client, and output the information on the console. After receiving information from the console, the client sends the input to the client, receives the echo data from the server, and then displays it on the console.

The client code is as follows:
Copy codeThe Code is as follows:
Package com. javapp. ch11;
Import java. io .*;
Import java.net .*;
/**
* Description: server and client programs with the "Echo" Function
*/
Public class EchoClientDemo {
// The Service port of the server.
Public static final int serverports = 990;
Public static void main (String [] args ){
Try {
// Establish a connection socket.
Socket s = new Socket ("localhost", SERVERPORT );
System. out. println ("socket =" + s );
// Input stream for creating a network connection.
BufferedReader in = new BufferedReader (new InputStreamReader (s
. GetInputStream ()));
// Create an automatically refreshed output stream for the network connection.
PrintWriter out = new PrintWriter (new BufferedWriter (
New OutputStreamWriter (s. getOutputStream (), true );
// Use System. in to construct InputStreamReader and then BufferedReader.
BufferedReader stdin = new BufferedReader (
New InputStreamReader (System. in ));
System. out. println ("Enter a string, Enter BYE to exit! ");
While (true ){
// Read the string input from the console and output it to the network connection, that is, send data to the server.
Out. println (stdin. readLine ());
// Read a row from the network connection to receive data from the server.
String str = in. readLine ();
// If the received data is null (if you press Enter directly instead of empty data), exit the loop and close the connection.
If (str = null ){
Break;
}
System. out. println (str );
}
S. close ();
} Catch (IOException e ){
System. err. println ("IOException" + e. getMessage ());
}
}
}

In the above client program. First, use the Socket class in the java.net package to establish a connection Socket. Then, the getInputStream method of the Socket object is applied to receive data from the server, And the getOuputStream method of the Socket object is used to send data to the server. After the input and output streams are created, you can read and write data in the same way as reading and writing files.

The server-side program code that supports multi-client "echo" is as follows:
Copy codeThe Code is as follows:
Package com. javapp. ch11;
Import java. io .*;
Import java.net .*;
/**
* Description: supports multi-client "Echo" server programs
*/
Public class EchoServerThreadDemo {
// The Service port of the server.
Public static final int serverports = 990;
Public static void main (String [] args ){
Try {
// The serial number of the connected client.
Int number = 1;
// Create a server listening socket.
ServerSocket s = new ServerSocket (SERVERPORT );
System. out. println ("Started:" + s );
While (true ){
// Wait and receive the request to establish a connection socket.
Socket incoming = s. accept ();
System. out. println ("Connection" + number + "accepted :");
System. out. println (incoming );
// Start a thread to transmit data between the server and client.
// The main program continues to listen for requests.
Thread t = new EchoThread (incoming, number );
T. start ();
Number ++;
}
} Catch (IOException e ){
System. err. println ("IOException ");
}
}
}
Class EchoThread extends Thread {
Private Socket s;
Int n;
Public EchoThread (Socket incoming, int number ){
S = incoming;
N = number;
}
Public void run (){
Try {
// Input stream for creating a network connection.
BufferedReader in = new BufferedReader (new InputStreamReader (s
. GetInputStream ()));
// Create an automatically refreshed output stream for the network connection.
PrintWriter out = new PrintWriter (new BufferedWriter (
New OutputStreamWriter (s. getOutputStream (), true );
System. out. println ("Hello! Enter BYE to exit .");
// Echo the client input.
While (true ){
// Read a row from the network connection to receive client data.
String line = in. readLine ();
// If the received data is null (if you press Enter directly instead of empty data), exit the loop and close the connection.
If (line = null ){
Break;
} Else {
If (line. trim (). equals ("BYE ")){
System. out. println ("The client" + n + "entered BYE! ");
System. out. println ("Connection" + n + "will be closed! ");
Break;
}
System. out. println ("Echo" + n + ":" + line );
// Output a row to the network connection, that is, send data to the client.
Out. println ("Echo" + n + ":" + line );
}
}
// Close the socket.
S. close ();
} Catch (IOException e ){
System. err. println ("IOException ");
}
}
}

In the server program, first create a server listening socket using the ServerSocket class in the java.net package. Then, the ServerSocket accept method is used to wait and receive user requests. When the server receives a connection request, it starts a thread to process data transmission between the server and the client separately. Receiving and sending server-side data is the same as sending and introducing client-side data.

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.