我正在尝试创建一个 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
吗?