在html5中使用,目前主流的浏览器都基本已经支持ws协议,只需要在js中直接使用即可
在html中:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="minimum-scale=1.0,maximum-scale=1,width=device-width,user-scalable=no"/>
<title>WS测试</title>
</head>
<body>
<section class="nav">
<div class="subNav">
<div class="slipMarquee" id="stock">
</div>
<div>
<input type="text" id="txt"/>
<button value="send" onclick="send();">send</button>
</div>
</div>
</section>
<script language="javascript" type="text/javascript">
window.WebSocket = window.WebSocket || window.MozWebSocket;
var socket = new WebSocket("ws://localhost:8888/echo");
// 注意这里的ip地址改为你自己的地址,创建sockect客户端
//如果是ssl,则需要把ws:// -> wss:// 如果是自签名证书,一般浏览器是不支持的
socket.onopen = function () {
socket.onclose = function (e) {// 关闭连接处理事件
alert('close the socket');
};
socket.onerror = function (msg) {// 出错处理事件
alert('error:' + msg);
};
};
socket.onmessage = function (e) {
// 收到消息处理事件,将收到的内容显示在页面上
document.getElementById('stock').innerHTML = '<font color =red>' + event.data + '</font>';
};
function send() {// 发送输入
socket.send(document.getElementById('txt').value);
}
</script>
</body>
</html>
在java中:
先导入一个java ws库的依赖
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.4.0</version>
</dependency>
示例:
public class WsClient {
static ThreadPool threadPool = new ThreadPool(ThreadPool.FixedThread, 10);
private static String PROTOCOL = "TLSv1.2";
public static void main(String[] args) throws Exception {
//System.setProperty("javax.net.debug", "all");
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
//开启ssl
WebSocketClientInst chatclient = new WebSocketClientInst(new URI("wss://localhost:8888/echo"));
//获取证书
String pkPath = ResourceUtils.getURL("classpath:clientStore.jks").getPath();
//ssl配置
SslConfig sSLConfig = new SslConfig();
sSLConfig.setKeyFile(pkPath);
sSLConfig.setKeyPassword("123456");
sSLConfig.setKeystorePassword("123456");
sSLConfig.setTrustFile(pkPath);
sSLConfig.setTrustPassword("123456");
//设置客户端模式
sSLConfig.setClientMode(true);
SSLContext sslContext = init(sSLConfig);
SSLSocketFactory factory = sslContext.getSocketFactory();
//设置ssl
chatclient.setSocketFactory(factory);
//连接服务器
chatclient.connectBlocking();
boolean loop = true;
int times = 0;
while (loop) {
times++;
if (ReadyState.OPEN.equals(chatclient.getReadyState())) {
chatclient.send("123"); //发送
Thread.sleep(1000);
} else {
System.out.println("还没ready, 继续进行中");
if (times <= 10) {
Thread.sleep(1000);
} else {
System.out.println("超时");
break;
}
}
}
}
/**
* 初始化
*
* @param config
*/
private static SSLContext init(SslConfig config) {
SSLContext sslContext = null;
try {
KeyManager[] keyManagers = null;
if (config.getKeyFile() != null) {
// 密钥库KeyStore
KeyStore ks = KeyStore.getInstance("JKS");
// 加载服务端的KeyStore,用于检查密钥库完整性的密码
ks.load(new FileInputStream(config.getKeyFile()), config.getKeystorePassword().toCharArray());
// 初始化密钥管理器
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, config.getKeyPassword().toCharArray());
keyManagers = kmf.getKeyManagers();
}
//初始化签名证书管理器
TrustManager[] trustManagers;
if (config.getTrustFile() != null) {
// 密钥库KeyStore
KeyStore ts = KeyStore.getInstance("JKS");
// 加载信任库
ts.load(new FileInputStream(config.getTrustFile()), config.getTrustPassword().toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ts);
trustManagers = tmf.getTrustManagers();
} else {
trustManagers = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}};
}
//初始化上下文
sslContext = SSLContext.getInstance(PROTOCOL);
sslContext.init(keyManagers, trustManagers, new SecureRandom());
} catch (Exception e) {
e.printStackTrace();
}
return sslContext;
}
}
//ws客户端
class WebSocketClientInst extends WebSocketClient {
public WebSocketClientInst(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connected");
}
@Override
public void onMessage(String message) {
System.out.println("got: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Disconnected");
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
}
}