数字证书

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){};
}
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值