2021-03-06

关于利用tomcat的websocket.jar包完成简单的后端向前端通信.

  1. 首先要写一个设置类,这个设置类需要实现ServerApplicationConfig接口,并重写getAnnotatedEndpointClasses方法和getEndpointConfigs方法。
  2. config类的代码如下
public class config implements ServerApplicationConfig{
	public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> arg0){
		
		
		return arg0;
		}

	public Set<ServerEndpointConfig> getEndpointConfigs(
			Set<Class<? extends Endpoint>> arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	}

3.写完设置类后,就该写我们的Server类了。主要用了注解。


@ServerEndpoint("/server")//这个是很重要,关系到前端 能否找到Server
public class Server {
   @OnOpen
   public  void  open(Session  session ){
   	System.out.println("建立了一个 webSocket通道!!!  sid:"+session.getId());
   	sendmsg(session);
   }
   @OnClose
   public void close(){
   	System.out.println("websocket关闭");
   }
   @OnMessage
   public   void  receiveMsg(Session session,String msg ){
   	System.out.println("收到信息啦 , 来自sid:"+session.getId());
   	System.out.println("信息:"+msg);
   }
   public void sendmsg(Session session){
   	session.getAsyncRemote().sendText("你好我是服务器");
   }
}

4.就是简单的jsp页面了

<%@ 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>
   
    <title>My JSP 'index.jsp' starting page</title>
    <script type="text/javascript">
    	function  ws_init(){
			 var target="ws://localhost:8080/mywebsocket/server";
    		  if ('WebSocket' in window) {
                  ws = new WebSocket(target);
              } else if ('MozWebSocket' in window) {
                  ws = new MozWebSocket(target);
              } else {
                  alert('WebSocket is not supported by this browser.');
                  return;
              }
    		  ws.onopen=function(){
	    				console.info("webSocket通道建立成功!!!");  
    		  };
    			
    	}
    
    </script>
  </head>
  <body>
  
  		<button  onclick="ws_init();"  >建立连接</button>
  			
  
  </body>
</html>

我在利用jar包的时候,没注意,结果jar包冲突了,所以大家要注意哦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值