JAVA中的SSL套接字连接池

kg7wmglp  于 2023-03-11  发布在  Java
关注(0)|答案(3)|浏览(213)

我正在创建一个SSL服务器-客户端。到目前为止,我所实现的是一个简单的服务器,可以与单个客户端(没有线程,也就是说)。现在,我想扩大这个应用程序的多个客户端,我想使用连接池。现在,我需要使用线程或有内置库,我可以使用。任何例子,链接等将工作。
PS:我试过谷歌搜索,但没有找到合适的链接。
下面是我的代码,如果需要:
服务器:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.*;

public class SSLServer {

    public static void main(String args[]){
        String ksname = "file.jks";
        char kspass[] = "pass".toCharArray();
        char ctpass[] = "pass".toCharArray();

        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(ksname), kspass);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, ctpass);
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(kmf.getKeyManagers(), null, null);
            SSLServerSocketFactory ssf = sc.getServerSocketFactory();
            SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(4321);
            //printServerSocketInfo(s);
            SSLSocket c = (SSLSocket) s.accept();
            //printSocketInfo(c);

            BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));

            w.write("Server starts\n");

            w.flush();
            String k = null;
            while((k = r.readLine()) != null){
                //do something
                if(k.equals("end"))
                    break;
                w.write(resolve(k));
                w.newLine();
                w.flush();
            }
            w.close();
            r.close();
            c.close();
            s.close();

        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (CertificateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }

    private static void printSocketInfo(SSLSocket s) {
          System.out.println("Socket class: "+s.getClass());
          System.out.println("   Remote address = "
             +s.getInetAddress().toString());
          System.out.println("   Remote port = "+s.getPort());
          System.out.println("   Local socket address = "
             +s.getLocalSocketAddress().toString());
          System.out.println("   Local address = "
             +s.getLocalAddress().toString());
          System.out.println("   Local port = "+s.getLocalPort());
          System.out.println("   Need client authentication = "
             +s.getNeedClientAuth());
          SSLSession ss = s.getSession();
          System.out.println("   Cipher suite = "+ss.getCipherSuite());
          System.out.println("   Protocol = "+ss.getProtocol());
    }

    private static void printServerSocketInfo(SSLServerSocket s) {
          System.out.println("Server socket class: "+s.getClass());
          System.out.println("   Socket address = "
             +s.getInetAddress().toString());
          System.out.println("   Socket port = "
             +s.getLocalPort());
          System.out.println("   Need client authentication = "
             +s.getNeedClientAuth());
          System.out.println("   Want client authentication = "
             +s.getWantClientAuth());
          System.out.println("   Use client mode = "
             +s.getUseClientMode());
    }

    private static String resolve(String p){
        //some implementation
        return "something";
    }

    }

委托单位:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class SSLClient {

    public static void main(String[] args){

        SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();

        try {
            SSLSocket c = (SSLSocket) f.createSocket("localhost", 4321);
            printSocketInfo(c);
            c.startHandshake();
            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
            BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));

            //to input hex code message
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String k = null;
            while((k = r.readLine()) != null){
                //send message to server
                System.out.println(k);
                System.out.flush();
                k = in.readLine();
                if(k.equals("."))
                    break;
                System.out.println(k);
                System.out.flush();
                w.write(k);
                w.newLine();
                w.flush();
            }
            w.close();
            r.close();
            c.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
yrwegjxp

yrwegjxp1#

你的服务器可以连接到多个客户端,在你的代码中你已经初始化了一个SSLServerSocket,它的任务是等待更多的客户端--每个客户端都将获得它自己的SSLSocket
如果你的服务器不能处理所有的客户端,你可以使用类似负载均衡器的东西,它可以将传入的请求分散到不同的服务器。

连接池通常在服务器内部使用-例如,用于与数据库通信。

这是否回答了您的问题?如果没有,您是否打算将请求分散到多个服务器,或者了解连接池的用途?

zz2j4svz

zz2j4svz2#

连接池在客户端实现。
在服务器端,您所能做的就是接受连接,并且在客户端关闭连接之前,或者在尝试读取第二个或后续请求时发生读取超时之前,不终止连接。

f87krz0w

f87krz0w3#

关于连接池,根据您的陈述,我猜您希望在Client SideServer Side中执行以下操作:这可以通过使用多线程来实现

  • 长时间运行的线程,它等待Socket/Socketchannel上的accept()方法

下面是一个代码片段服务器端

ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
        while(!isStopped()){
                try {
    ServerSocketChannel socChnl1 = ServerSocketChannel.open();
            socChnl1.socket().bind(new InetSocketAddress(port));
                    SocketChannel obj=socChnl1 .accept();
                    
                    threadPool.execute(new WorkerThread(obj);
                    
                    
                } catch (IOException e) {
                    e.printStackTrace();
                }

对于客户端

相关问题