Java中实现 Client-Server 体系1 -- 基本实现

来源:互联网 发布:echart动态获取数据 编辑:程序博客网 时间:2024/05/17 08:24

1.相关类的介绍

服务器程序不同于客户机端的程序,它需要初始化一个端口进行监听,遇到连接呼叫,才与相应的客户机建立连接。Java.net包的ServerSocket类包含了编写服务器系统的全部所需功能,而客户端软件通常使用java.net包中的核心类Socket与服务器的某个端口建立连接。

 

2.单线程客户端程序建立步骤:

1)建立socket,指明连接地址和端口。

2)建立socket相应的输入流和输出流。

3)利用这些IO进行读写。

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {

        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            socket = new Socket("127.0.0.1", 3721);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to: taranis.");
            System.exit(1);
        }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    String userInput;

    while ((userInput = stdIn.readLine()) != null) {//read from keyboard
        out.println(userInput);//send the info to server
        System.out.println("echo: " + in.readLine());//read from server
    }

    out.close();
    in.close();
    stdIn.close();
    socket.close();
    }
}

 

3.单线程服务器程序建立步骤:

1)初始化ServerSocket,将参数port指定的端口初始化作为该服务器的端口,监听客户机连接请求。

2)创建一个socket实例,调用其accept方法接受客户呼叫。Accept()方法直到有连接请求才返回通信套接字(Socket)的实例。通过这个实例的输入、输出流,服务器可以接收用户指令,并将相应结果回应客户机。

3)使用while()循环不断读取客户端

import java.net.*;
import java.io.*;

public class Server {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(3721);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 3721.");
            System.exit(1);
        }

        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String line;

        while ((line = in.readLine()) != null) {//read, when nothing ,it will block.
             System.out.println("Client send : "+line);
             out.println(line + " signed by server ");//send back with the “signed by server”.
             if (line.equals("Bye."))
                break;
        }
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}

 

4.多线程服务器程序的建立步骤:

往往单线程服务器难以满足实际的并发需求,所以建立多线程服务器程序是实际必须的。一般建立多线程服务器程序的模式如下:

while (true) {    accept a connection ;    create a thread to deal with the client ;end while
 
在这个程序中,我们将Server端的改为这个模式:

import java.io.IOException;
import java.net.ServerSocket;

public class MultiServer {
     public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = null;
            boolean listening = true;

            try {
                serverSocket = new ServerSocket(3721);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 3721.");
                System.exit(-1);
            }

            while(listening)
                new ServerThread(serverSocket.accept()).start();
            serverSocket.close();
        }
}

 

在创建线程方面,我们需要多线程模式,其实就是把服务器端的能力放在了这个类中,我们可以在后边的代码中看到,其实这个类中的功能与原先单线程的部分大同小异,也就是把功能放在了多线程中的run()方法中。

import java.net.*;
import java.io.*;

public class ServerThread extends Thread {
    private Socket socket = null;

    public ServerThread(Socket socket) {
    super("Thread");
    this.socket = socket;
    }

    public void run() {

    try {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        String line;

        while ((line = in.readLine()) != null) {
             System.out.println("Client send : "+line);
             out.println(line + " signed by server ");
             if (line.equals("Bye."))
                break;
        }
        out.close();
        in.close();
        socket.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    }
}

原创粉丝点击