java WebSocket通信,聊天室实例
1:jar包下载
1.1:方式一
直接下载jar包:点我下载jar包
1.1:方式二
配置maven仓库
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.7</version>
</dependency>
2:WebSocket客户端部分
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<html>
<head>
<title>websocket.html</title>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<div style="box-shadow: 0 0 10px #dddee1;overflow:auto;margin:10%;width:80%;height:20em;margin-bottom:0;">
<div style="text-align:center">聊天室(<h6 style="display:inline">当前在线人数:<h6 id="people" style="display:inline;color:#19be6b"></h6></h6>)</div>
<div id="message"></div>
</div>
<div style="text-align:center;margin-left:10%;width:80%;">
<input id="text" type="text"></input><button onclick="send()">发送</button>
</div>
<script type="text/javascript" src="./jquery-3.0.0.min.js"></script>
<script type="text/javascript">
var timestamp = Date.parse(new Date());
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/Test/chat/"+timestamp);
console.log("link success")
}else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("连接错误");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("连接成功");
}
console.log("-----")
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
//document.getElementById('message').innerHTML += innerHTML + '<br/>';
console.log(innerHTML);
var msgAndPeople = innerHTML.split(",");
$("#message").append(msgAndPeople[0]+"<br/>");
document.getElementById("people").innerHTML=msgAndPeople[1];
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
document.getElementById('text').value="";
}
</script>
</html>
3:WebSocket服务端部分
@ServerEndpoint(value="/chat/{username}")
public class WebSocket {
private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
System.out.println("username的值为"+username);
System.out.println("session的值为"+session);
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
System.out.println("已连接");
sendMessageAll("");
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
System.out.println("接收到消息");
System.out.println(message);
// JSONObject jsonTo = JSONObject.fromObject(message);
//
// String mes = (String) jsonTo.get("message");
// if (!jsonTo.get("To").equals("All")){
//
// sendMessageTo(mes, jsonTo.get("To").toString());
//
// }else{
//
// sendMessageAll("给所有人");
//
// }
sendMessageAll(message);
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for (WebSocket item : clients.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message+","+onlineCount);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}