WebSocketDemo程序

  • L9_655196
    了解作者
  • 733.9KB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-06-15 10:53
    上传日期
NULL 博文链接:https://bbwang8088.iteye.com/blog/2386577
WebSocketServerDemo.zip
内容介绍
package web.sinage.fhs; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; import org.apache.catalina.websocket.WsOutbound; @SuppressWarnings("deprecation") public class SinageWebSocketServlet extends WebSocketServlet { private static final long serialVersionUID = -2581942001009336822L; /* 保存所有WebSocket连接的List结构 */ public static List<WebSocketMessageInbound> connsList = new ArrayList<WebSocketMessageInbound>(); public SinageWebSocketServlet() { super(); } protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) { return new WebSocketMessageInbound(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); } /** * 本类在新建WebSocket实例时自动实例化,只要实现内部受保护方法即可. * * @author wang-bingbing * */ public class WebSocketMessageInbound extends MessageInbound { protected void onClose(int status) { super.onClose(status); connsList.remove(this); } protected void onOpen(WsOutbound outbound) { super.onOpen(outbound); connsList.add(this); /* 对第一次连接的回应 */ sendTextMessage(CharBuffer.wrap("Hello,WebSocket client!".toString())); } /** * 重载方法 * 接受二进制数据 */ @Override protected void onBinaryMessage(ByteBuffer message) throws IOException { System.out.println("Receive binary data: ["+message.toString()+"]"); sendBinaryMessage(message); } /** * 重载方法 * 接受文本数据 */ @Override protected void onTextMessage(CharBuffer message) throws IOException { System.out.println("Receive text data: ["+message.toString()+"]"); sendTextMessage(message); } /** * 自定义的发送二进制数据方法 * @param message */ protected void sendBinaryMessage(ByteBuffer message) { try { this.getWsOutbound().writeBinaryMessage(message); this.getWsOutbound().flush(); System.out.println("Send binary data: ["+new String(message.array())+"] successed!"); } catch (IOException e) { System.out.println("Send binary data: ["+new String(message.array())+"] failed!"); } } /** * 自定义的发送文本数据方法 * @param message */ protected void sendTextMessage(CharBuffer message) { try { this.getWsOutbound().writeTextMessage(message); this.getWsOutbound().flush(); System.out.println("Send text data: ["+new String(message.array())+"] successed!"); System.out.println("5"+2); } catch (IOException e) { System.out.println("Send text data: ["+new String(message.array())+"] failed!"); } } } }
评论
    相关推荐