欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数字证书

程序员文章站 2022-07-12 21:56:10
...
1.Socket服务端

package com.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;

public class ServerSocketTest {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
// ServerSocket ss = new ServerSocket(6666);
/**
* 可以通过keytool生成证书
*/
String userHome = System.getProperty("user.home");
System.setProperty("javax.net.ssl.keyStore", userHome + "/.keystore");
System.setProperty("javax.net.ssl.keyStorePassword", "123456");
SSLServerSocketFactory sslFactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket)sslFactory.createServerSocket(6666);

for (int i = 0; i < 5; i++) {
final Socket socket = ss.accept();
new Thread() {
public void run() {
InputStream is = null;
OutputStream os = null;
try {

is = socket.getInputStream();
os = socket.getOutputStream();

byte[] buf = new byte[1024];
int len = 0;

len = is.read(buf);
System.out.println(new String(buf, 0, len));

os.write("hello".getBytes());

} catch (Exception ex) {
ex.printStackTrace();
}finally{
try{os.close();}catch(Exception e){};
try{is.close();}catch(Exception e){};
try{socket.close();}catch(Exception e){};
}
};
}.start();
}

}

}



2.Socket客户端

package com.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

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

public class SocketTest {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
// Socket socket = new Socket("192.200.216.67",6666);
/**
* 客户端,证书可以导入JAVA_HOME\jre6\lib\security\cacerts下,或设置系统属性
* javax.net.ssl.trustStoreType
* javax.net.ssl.trustStore
*/
SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)factory.createSocket("192.200.216.67",6666);

InputStream is = null;
OutputStream os = null;
try {

is = socket.getInputStream();
os = socket.getOutputStream();

os.write("world".getBytes());

byte[] buf = new byte[1024];
int len = 0;

len = is.read(buf);
System.out.println(new String(buf, 0, len));

} catch (Exception ex) {
ex.printStackTrace();
}finally{
try{os.close();}catch(Exception e){};
try{is.close();}catch(Exception e){};
try{socket.close();}catch(Exception e){};
}
}

}