您的位置:首页 > 其它

一个基于webSocket实现前后端通信的小demo

2018-01-09 11:27 471 查看
一般的web项目都是前台向后台发送消息,但是有些时候我们也需要从后端向前台发送消息,比如说zfb的回调信息,微信的模板推送消息等,下面通过Eclipse+Tomcat实现一个前后台通信的小demo;

先创建一个web项目  index.jsp写一个简单的页面来显示消息

<%@ page language="java" pageEncoding="UTF-8" %>

<html>

<head>

<title>Java后端WebSocket的Tomcat实现</title>

</head>

<body>
Welcome
<br />
<input id="text" type="text" />
<button onclick="send()">发送消息</button>
<hr />
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr />
<div id="message"></div>
<script>
var websocket = null;
if('WebSocket' in window){
websocket = new WebSocket("ws://127.0.0.1:8080/testWebSocket/websocket")
}else{
alert("当前浏览器不支持websocket")
}
websocket.onerror = function(){
setMessageInHtml("发送错误");
}
websocket.onopen = function(){
setMessageInHtml("建立连接")
}
websocket.onmessage  = function(event){
setMessageInHtml(event.data);
}
websocket.onclose = function(){
setMessageInHtml("关闭WebSocket连接")
}
window.onbeforeunload = function(){
closeWebsocket();
}
function setMessageInHtml(message){
document.getElementById('message').innerHTML += message+'</br>'
}
function closeWebsocket(){
websocket.colse();
}
function send(){
var msg = document.getElementById('text').value;
websocket.send(msg);
}
</script>

</body>

</html>

先在maven导入需要的jar包

</dependency>

    <dependency>

         <groupId>javax</groupId>

         <artifactId>javaee-api</artifactId>

         <version>7.0</version>

         <scope>provided</scope>
</dependency>

再来新建一个java文件package testWebSocket;

import java.io.IOException;

import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;

import javax.websocket.OnError;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")

public class WebSocketTest {
//记录当前连接数
private static int onlineCount = 0;
//记录与每个客服端的连接
private static CopyOnWriteArraySet<WebSocketTest> arraySet = new CopyOnWriteArraySet<WebSocketTest>();
//状态管理
private Session session;
//当打开连接时
@OnOpen
public void onOpen(Session session) {
// TODO Auto-generated method stub
this.session = session;
arraySet.add(this);
addOnlineCount();
System.out.println("有新连接进来,当前连接数为:" + getOnlineCount());
}

//当关闭连接时
@OnClose
public void onClose() {
// TODO Auto-generated method stub
arraySet.remove(this);
subOnlineCount();
}

//收到消息
@OnMessage
public void onMessage(String message,Session session) {
// TODO Auto-generated method stub
System.out.println("从客户端收到的消息是:" + message);
//群发消息
for (WebSocketTest webSocketTest : arraySet) {
try {

//向客户端发送消息
webSocketTest.sendMessage(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
@OnError
public void OnError(Session session,Throwable error) {
// TODO Auto-generated method stub
System.out.println("发送错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}

public static synchronized void subOnlineCount() {
onlineCount--;
}

public static synchronized void addOnlineCount() {
onlineCount++;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: