NutzCN Logo
问答 websocket的demo中dao注入不了
发布于 2049天前 作者 qq_c2f129d2 1864 次浏览 复制 上一个帖子 下一个帖子
标签:
package net.wendal.nutz.module;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

import org.h2.util.IntIntHashMap;
import org.h2.util.New;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.ioc.loader.combo.ComboIocLoader;
import org.nutz.mvc.annotation.At;

import net.wendal.nutz.bean.News;
 
/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@IocBean()
@ServerEndpoint(value="/websocket",configurator=GetHttpSessionConfigurator.class)
public class WebSocketTest{
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
     
    @Inject
    private Dao dao;
 
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();
 
    private static Map map=new HashMap<>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
 
    public Session getSession() {
		return session;
	}
	public void setSession(Session session) {
		this.session = session;
	}


	private static int newsize=0;
    public List<News> getNews(){
    	List<News> news=new ArrayList<>();
    	System.out.println(dao);//-----------------------------这里打印为null
    	//news=dao.query(News.class, null);
    	return news;
    }
    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session,EndpointConfig config){
    	HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
    	String name=httpSession.getAttribute("name").toString();
    	if (name==null) {
			name="nobody!";
		}
    	map.put( session.getId(),name);
    	System.out.println("key="+session.getId()+"and the value="+name);
    	this.session = session;  
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }
 
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }
 
 
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        List<News> news=getNews();
      
    	if(newsize!=news.size()){
    		newsize=news.size();
          for(WebSocketTest item: webSocketSet){
          try {
        	  for(int i=0;i<newsize;i++)
        	  {
        		  News n=news.get(i);
        		  String name=n.getUsr();
        		  String id=(String)item.getSession().getId();
        		  String idsname=(String)map.get(id);
        		  if(name.equals(idsname)){
        			  item.sendMessage(name+":"+n.getMsg());
        		  }
        	  }
              
          } catch (IOException e) {
              e.printStackTrace();
              continue;
          }
      }
    	}
    	
    	
    	//System.out.println("来自客户端的消息:" + message);
//        String id=session.getId();
//        int i;
//        String name=(String) map.get(id);
//        System.out.println("id from="+id+"name from="+name);
//        System.out.println("来自客户端的消息"+name+":" + message);
//        //群发消息
//        for(WebSocketTest item: webSocketSet){
//            try {
//                item.sendMessage(name+":"+message);
//            } catch (IOException e) {
//                e.printStackTrace();
//                continue;
//            }
//        }
    }
 
 
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }
 
 
    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }
 
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
 
    public static synchronized void addOnlineCount() {
        WebSocketTest.onlineCount++;
    }
 
 
    public static synchronized void subOnlineCount() {
        WebSocketTest.onlineCount--;
}
}
4 回复

configor=GetHttpSessionConfigurator.class

得用插件里面的configor才行的

这要怎么用啊,我是dao注入不了,打印dao的时候是null,使用dao会报空指针异常

你看的是什么demo? 需要注入的话,要用configurator=NutWsConfigurator.class

https://github.com/nutzam/nutzmore/tree/master/nutz-plugins-websocket

demo是找的网上的websocket的demo,我想使用dao来处理数据库的,不过应该也用不了太多数据库操作,所以使用jdbc那个应该也可以

添加回复
请先登陆
回到顶部