Java WebSocket

xiaoxiao2025-06-01  26

*1导入tomcat中的两个jar包 2实现后端服务器类 实现思路 1.创建CopyOnWriteArraySet<>类型安全集合 创建Session对象 2.实现 onOpen():将当前对象this加入到集合中 onErrer() :提示错误 onMessage() :onMessage()发送消息 用s.session.getBasicRemote().sendText(“内容”)发送 onClose():将当前对象从集合中移除

package cn.Test.Test; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/websocket1") public class WebSocket { private static CopyOnWriteArraySet<WebSocket> soc=new CopyOnWriteArraySet<WebSocket>(); private Session session; @OnOpen public void onOpen(Session session){ this.session=session; soc.add(this); System.out.println("新连接开始"); } @OnClose public void onClose(Session session){ soc.remove(this); System.out.println("一连接关闭"); } @OnMessage public void onMessage(String Mession,Session session){ for (WebSocket s : soc) { try { s.session.getBasicRemote().sendText(Mession); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void onError(Session session,Throwable e){ e.getStackTrace(); } public void sendMessage(String Message){ } }

3前端实现 实现思路: 1.创建websocket对象 用 ‘WebSocket’ in window判断浏览器是否支持websocket 支持则创建 不支持提示客户端 2.实现方法 (这几个方法就是后端的回调方法了 就像ajax的success呢个回调 成功就会执行) onerror():在div中添加内容 错误 onopen():在div中添加内容 连接成功 onmessage(event):调用websocket.send(var Message)方法 参数为内容 onclose():在div中添加内容 连接关闭 3.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'MyJsp.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <div> <input type="text" id="txt"/> <button id="send">发送</button> </div> <div id="aa"> </div> </body> <script> var div=document.getElementById("aa"); document.getElementById("send").onclick=function(){ var txt=document.getElementById("txt").value; websocket.send(txt); } var websocket=null; if('WebSocket' in window){ websocket = new WebSocket("ws://192.168.10.44:8080/WebSocket/websocket1"); } else{ alert("浏览器不支持WebSocket"); } websocket.onopen=function(){ div.innerHTML=div.innerHTML+"打开连接成功<br/>"; } websocket.onclose=function(){ div.innerHTML=div.innerHTML+"关闭连接成功<br/>"; } websocket.onmessage=function(event){ div.innerHTML=div.innerHTML+event.data+"<br/>"; } </script> </html>
转载请注明原文地址: https://www.6miu.com/read-5031091.html

最新回复(0)