Home > Web Front-end > JS Tutorial > body text

Introduction to the method of using Java to implement simple server/client echo function_Basic knowledge

WBOY
Release: 2016-05-16 17:34:47
Original
1628 people have browsed it

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

If a connection is to be established, one machine must run a process waiting for the connection, while another machine must try to reach the first machine. This phone system is similar: one party must initiate the call, while the other party must wait for the phone call.

java network model diagram

The following uses a server and client with "echo" function to introduce the application of java.net package to write network applications.

The main function of this example is that the server-side program waits for the client's input, then echoes the read information to the client, and outputs it on the server-side console at the same time. After the client receives the information from the console, it sends input to the client, receives the echo data from the server, and then displays it on the console.

The client program code is as follows:

Copy code The code is as follows:

package com.javapp.ch11;
import java.io.*;
import java.net.*;
/**
* Description: Server-side and client-side programs with "echo" function
*/
public class EchoClientDemo {
// Server-side service port.
public static final int SERVERPORT = 990;
public static void main(String[] args) {
try {
// Establish a connection socket.
Socket s = new Socket("localhost",SERVERPORT);
System.out.println("socket = " s);
// Create the input stream of the new network connection.
BufferedReader in = new bufferedReader
           PrintWriter out = new PrintWriter(new BufferedWriter(
            new OutputStreamWriter(s.getOutputStream())), true);                               Reader.
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());
string str = in.readline ();
// If the received data is empty (if you press Enter directly, not empty data), then exit the loop and close the connection.
                                                                                                                                                                                                                                                                                                                                                                                                                                                    . (IOException e) {
        System.err.println("IOException"                                                                           . First, use the Socket class in the java.net package to establish a connection socket, then use the getInputStream method of the Socket object to receive data from the server, and use the getOuputStream method of the Socket object to send data to the server. After creating the input and output streams, you can read and write data in the same way as files.

The "echo" server-side program code that supports multiple clients is as follows:




Copy the code


The code is as follows:

package com.javapp.ch11;
import java.io.*;
import java.net.*;
/**
* Description: Supports multi-client "echo" server-side program
*/
public class EchoServerThreadDemo {
// Server-side service port.
public static final int SERVERPORT = 990;
public static void main(String[] args) {
try {
// The serial number of the connected client.
             int number = 1;
                                                                                                                                                                                                                           int number = 1;
ServerSocket s = new ServerSocket(SERVERPORT);
System.out.println("Started: " s);
while (true) {
, establish connection socket Character.
Socket incoming = s.accept();
System.out.println("Connection " number " accepted: ");
System.out.println(incoming);
                                                                   Threads are used for data transmission between the server and the client.
                                                                                                                                                         // The main program continues to monitor whether there are requests coming.
                                                                       } 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 {

BufferedReader in = new bufferedReader
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(s.getOutputStream())),true);
System.out.println("Hello! Enter BYE to exit." );
                                                                          // Echo the client’s input.
While (TRUE) {
// Read a line from the network to receive data from the client.
string line = in.readline ();
// If the received data is empty (if you press Enter directly, not empty data), then exit the cycle and close the connection.
                if (line ==                                                              BYE")) {
                          System.out.println( "The client " n " entered BYE!");
                              System.out. }
System.out.println ("Echo" n ":" line);
// connect to the network to output a row, that is, send data to the client.
                out.println("Echo " n ": " line);
s.close();
} catch (IOException e) {
System.err.println("IOException");
}
}
}


In the server-side program, first create a server-side listening socket using the ServerSocket class in the java.net package. Then use the accept method of the ServerSocket class to wait for and receive user requests. When the server receives a connection request, it starts a thread to handle the data transmission between the server and the client separately. The receiving and sending of server-side data is the same as the sending and introduction of client-side data described above.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template