在服务器端打开一个安全套接字

时间:2016-11-22 08:18:29

标签: java sockets ssl

我有一个服务器应用程序,它打开一个套接字,然后监听在该套接字上建立的任何连接。

public Server(){
    try {
        ServerSocket sSocket = new ServerSocket(nPort);
        System.out.println("Server started at: " + new Date());
        System.out.println("===============================================\n");

        //Loop that runs server functions
        while(true) {
            //Wait for a client to connect
            Socket socket = sSocket.accept();
            socket.setSoTimeout(30000);
            //Create a new custom thread to handle the connection
            ClientThread cT = new ClientThread(socket, nPort);
            //Start the thread!
            new Thread(cT).start();  
        }
    } 
    catch(IOException ex) {ex.printStackTrace();}
}

每当尝试新连接时,都会使用ClientThread类启动新线程。 ClientThread类有一个run方法,可以完成所有需要完成的事情(读取输入,发送响应等)。

public class ClientThread implements Runnable{
private Socket threadSocket;
private int nPort = 0, maxCon = 2;

//This constructor will be passed the socket
public ClientThread_v3(Socket socket, int port){
    threadSocket = socket;
    nPort = port;
}

public void run(){
    System.out.println("New connection at " + new Date() + "\n");
    try {
        DataInputStream in = new DataInputStream (threadSocket.getInputStream());
        out = new DataOutputStream (threadSocket.getOutputStream());                  
        while (running){ 
            // do some stuff ....

            // go to sleep
            Thread.sleep(1000);
        }
    } 
    catch (IOException ex) {ex.printStackTrace();} 
    catch (InterruptedException ex) {ex.printStackTrace();}
    finally {
        try {
            threadSocket.close();
            System.out.println("Connection closed.\n");
        } catch (IOException ex) {ex.printStackTrace();}
    }
}}

我的问题是如何使套接字连接安全?我该如何打开安全连接? 我不想使用任何HTTP包,希望将其保存为套接字连接。 任何帮助,将不胜感激。谢谢。

0 个答案:

没有答案