客户端代码如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; public class SslClient { private SSLSocket s; private DataOutputStream out; private DataInputStream in; public SslClient() throws IOException { } public void sendMessage(Socket s, String msg) { try { out = new DataOutputStream(s.getOutputStream()); String jsonString = msg; out.write(jsonString.getBytes()); } catch (IOException e) { } } public String receiveMessage(Socket s) { try { in = new DataInputStream(s.getInputStream()); BufferedReader socketIn = new BufferedReader(new InputStreamReader(in));// 接受到 String res = socketIn.readLine(); if (res == null || res.equals("null")) { res = ""; } return res; } catch (Exception e) { return ""; } } public String talk(String ip, int port, String trustStore, String trustStorePassword, int socketOutTime, String msg) throws Exception { try { int connectTimeout = socketOutTime * 1000;//设置超时时间 System.setProperty("javax.net.ssl.trustStore", trustStore);// 设置可信任的密钥仓库 System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); // 设置可信任的密钥仓库的密码 SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();// 利用工厂来创建SSLSocket安全套接字 s = (SSLSocket) sslsf.createSocket(); s.connect(new InetSocketAddress(ip, port), connectTimeout); s.startHandshake(); System.out.println("向服务器发送:" + msg); sendMessage(s, msg); // 发字符串 String result = receiveMessage(s); System.out.println("服务器返回:" + result); out.close(); in.close(); if (s != null) { s.close(); } return result; } catch (Exception e) { e.printStackTrace(); out.close(); in.close(); if (s != null) { s.close(); } return ""; } } public static void main(String[] args) throws Exception { SslClient c = new SslClient(); String responseMsg = c.talk("xxx.xxx.xxx.xxx", 8089, "D:\\xxxx\\shfqtruststore.jks", "123456", 5, "test\n"); System.out.println(responseMsg); } } |