maven导入一个包即可
<dependency>
<groupId>javax.websocket</groupId><artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
</dependency>
注意:tomcat版本最好是8.0,原来用的7.0版本建立不了链接
简单的发送消息的页面
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/c.js"></script>
</head>
<body >
<div>
<p>
<input type="text" placeholder="type and press enter to chat" id="chat" />
</p>
<input type="button" value="send" class="btn" id="send">
<div id="console-container">
<div id="console"></div>
</div>
</div>
</body>
</html>
c.js封装了websock的连接:
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
//创建webSocket,
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
//Console.log('Error: WebSocket is not supported by this browser.');
// return;
Chat.socket = new SockJS(
"http://localhost:8080/websocket5/sockjs/webSocketServer");
}
//建立websocket的事件,可以用来做一些初始化操作
Chat.socket.onopen = function() {
$("#send").click(function(){
Chat.sendMessage();
});
};
//绑定关闭事件
Chat.socket.onclose = function() {
document.getElementById('chat').onkeydown = null;
};
//监