2

我正在尝试创建一个 EndPoint 文件。所以我创建了一个文件名ServerEndPointDemo.groovy

package com.akiong

import grails.util.Environment
import grails.util.Holders

import javax.servlet.ServletContext
import javax.servlet.ServletContextEvent
import javax.servlet.ServletContextListener
import javax.servlet.annotation.WebListener
import javax.websocket.EndpointConfig
import javax.websocket.OnClose
import javax.websocket.OnError
import javax.websocket.OnMessage
import javax.websocket.OnOpen
import javax.websocket.Session
import javax.websocket.server.PathParam
import javax.websocket.server.ServerContainer
import javax.websocket.server.ServerEndpoint
import javax.websocket.EncodeException

import javax.servlet.annotation.WebListener
import java.util.concurrent.CopyOnWriteArraySet

@WebListener
@ServerEndpoint(value="/chat/test/{username}")

public class ServerEndPointDemo implements ServletContextListener {
    private static HashMap<String, String> usersMap = new HashMap<String, String>();
    private static final Set<ServerEndPointDemo> connections = new CopyOnWriteArraySet<>();
    private String username
    private Session session

    @OnOpen
    public void  handleOpen(Session session,@PathParam("username") String user){
        System.out.println("-------------------------------------");

        System.out.println(session.getId() + " has opened a connection");
        println "user = "+user

        connections.add(this);
        this.username   = user
        this.session    = session

        addUserToMap(username,session.getId())

        try{
            def ctx = Holders.applicationContext
            chatService = ctx.chatService
        }
        catch (Exception e){
            println "e = "+e
        }

    }

    @OnClose
    public void  handleClose(Session session){  
        System.out.println("Session " +session.getId()+" has ended");  
    }

    @OnMessage
    public String handleMessage(String message,Session session){
        chatService.saveSessionAdminJava(session.getId())    
    }

    @OnError
    public void  handleError(Throwable t){
        println "error ~"
    }  

    private void sendMessageToAll(String message){
        println "session.size() = "+sessions.size()
        for(Session s : sessions){
            try {
                s.getBasicRemote().sendText(message);
                println "sent to session = "+s.getId()
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
`

我尝试使用此代码从服务调用方法:

try {
    def ctx = Holders.applicationContext
    chatService = ctx.chatService
} catch (Exception e) {
    println "e = " + e
}

这是我的服务:

package com.akiong.services

import com.akiong.maintenance.Chat

class ChatService {

    def serviceMethod() {

    }

    def saveSessionAdminJava(def sessionJava) {
        println "jaln!!!"
        def chatInstance = Chat.findByIsAdmin("1")
        chatInstance.sessionJava = sessionJava
        chatInstance.save(failOnError: true)
    }
}

但是在我尝试运行这段代码之后,我收到了这个错误:

Error : groovy.lang.MissingPropertyException: No such property: chatService for
class: com.akiong.ServerEndPointDemo

有人知道如何从服务调用方法到文件src/groovy吗?

4

2 回答 2

1

所以这就是问题所在。您编写的代码对于注入服务是正确的:

try {
    def ctx = Holders.applicationContext
    chatService = ctx.chatService
} catch (Exception e) {
    println "e = "+e
}

但是chatService在您的班级的任何地方都没有定义。因此,即使您的handleOpen方法被调用,也必须MissingPropertyException被抛出,但由于您已经处理了顶级Exception类(不应该鼓励),因此您的方法中的异常handleOpen被抑制了。

现在,稍后在您的handleMessage方法中,同样的问题再次出现chatService未定义,因此您得到了您在问题中发布的异常。

所以,你现在知道答案了 :-) 只需chatService在你的ServerEndPointDemo类中定义。

更新:

public class ServerEndPointDemo implements ServletContextListener {
    private static HashMap<String, String> usersMap = new HashMap<String, String>();
    private static final Set<ServerEndPointDemo> connections = new CopyOnWriteArraySet<>();
    private String username
    private Session session

    def chartService    // Initialize here
    // rest of your code
}
于 2015-11-20T10:41:13.157 回答
-1
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH

class MyClass{
    private static final log = LogFactory.getLog(this)
    def ctx = AH.application.mainContext
    def authService=ctx.authService

    def method(){
        log.debug "into MyClass method"
    }
}
于 2015-11-20T09:26:39.280 回答