一个基于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++;
}
}
先创建一个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++;
}
}
相关文章推荐
- JAVA基于websocket实时通信的实现—GoEasy
- netty框架的学习笔记 + 一个netty实现websocket通信案例
- 基于Delphi实现客户端服务端通信Demo
- Golang基于websocket实时通信的实现—GoEasy
- 基于HTML5 WebSocket的Web实时通信机制的研究与实现
- Ruby基于websocket实时通信的实现—GoEasy
- 基于Struts2和hibernate的WebSocket聊天室的实现教程六:界面原型及通信请求
- .NET基于websocket实时通信的实现—GoEasy
- windwos平台下C++实现一个基于UDP的C/S模式通信示例
- 基于https实现webSocket通信实时在web页面输出日志(两个日志输出)
- C#基于websocket实时通信的实现—GoEasy
- web即时通信2--基于Spring websocket实现web聊天室
- enginx:基于openresty,一个前后端统一,生态共享的webstack实现
- 写一个Tomcat+Okhttp实现的聊天websocket聊天框架(一)-- 完成客户端和服务端的通信
- Python基于websocket实时通信的实现—GoEasy
- PHP基于websocket实时通信的实现—GoEasy
- 基于HTML5 WebSocket的Web实时通信机制的研究与实现
- PHP基于websocket实时通信的实现—GoEasy
- 一个基于netty的websocket聊天demo
- 基于Delphi实现客户端服务端通信Demo