java 实现websocket

前端HTML实现:

<html>
<head>
</head>
<body>
<div id="valueLabel">websocket</div>
<input id="speak" />
<input type="button" onclick="say()" value="send"/>
<input type="button" onclick="closews()" value="Close" style="display:none;" id="closebtn"/>
<input type="button" onclick="connws()" value="Connection" id="connbtn" style="display:inline"/>
<input type="button" onclick="loginws()" value="Login" id="loginbtn" style="display:inline"/>
<script type="text/javascript">
var socket;
var speak=document.getElementById("speak");
var valueLabel = document.getElementById("valueLabel");

function connws() {
valueLabel.innerHTML = "";
document.getElementById("closebtn").style.display="inline";
document.getElementById("connbtn").style.display="none";
var ws = new WebSocket("ws://127.0.0.1:9999","kkss");


ws.onmessage = function(evt) {

valueLabel.innerHTML = valueLabel.innerHTML + " " + evt.data;

};

 

ws.onclose = function(evt) {

valueLabel.innerHTML = "onClose";
document.getElementById("connbtn").style.display="inline";
document.getElementById("closebtn").style.display="none";

};

 

ws.onopen = function() {
ws.send("Hello, All guys");

};

socket = ws;

}

 

function say()

{

socket.send(speak.value);

}


function closews()
{socket.send("{"cmd":"close"}");
}

function loginws()
{socket.send("{"cmd":"login","uid":"dhk"}");
}

</script>
</body>
</html>


采用Jkas框架的后端JAVA实现:

配置开启WEBSOCKET功能:

[SOCKET]

;是否开启socket
socket_enable=1

;socket端口
socket_port=9999

;socket调用包名设置
socket_package=test.z.socket

;for websocket的验证协议
socket_protocol=kkss


package test.z.socket;
import org.jkas.core.JkasSocket;
public class Test extends JkasSocket
{ public String index()
{ send("hello");
  return "a";
}
}


结果:

微信图片_20190226104449.png