grails javax.websocket问题

时间:2014-07-22 13:52:29

标签: grails websocket

Grails 2.3.7 - Java 1.7

我已经看到以下在核心java中使用的示例并作为演示工作,试图在Grails中实现相同的功能,我知道有一些围绕websockets的插件但是我试图自己解决这个问题:

控制器1

package chat

class TestController {

    def index() { }
}

index.gsp中

<!DOCTYPE html>
<html>
    <head>
        <meta name="layout" content="main">
        <g:set var="entityName" value="${message(code: 'admin.label', default: 'Admin')}" />
        <title><g:message code="default.create.label" args="[entityName,BAH,BAH]" /></title>
    </head>
    <body>  
    <form>
    <input id="textMessage" type="text">
    <input type="button" value="send" onClick="sendMessage();">
    </form>
    <br>
    <textarea id="messagesTextarea" rows="10" cols="50">
    </textarea>

    <script type="text/javascript">
        var webSocket=new WebSocket("ws://localhost:8080/chat/testing");
        var messagesTextarea=document.getElementById("messagesTextarea");
        var textMessage=document.getElementById("textMessage");
        webSocket.onopen=function(message) {processOpen(message);};
        webSocket.onmessage=function(message) {processMessage(message);};
        webSocket.onclose=function(message) {processClose(message);};
        webSocket.onerror=function(message) {processError(message);};
        function processOpen(message) {
            messagesTextarea.value +=" Server Connect.... "+"\n";
        }
        function processMessage(message) {
            messagesTextarea.value +=" Receive from Server ===> "+ message.data +"\n";
        }
        function sendMessage() {
            if (textMssage.value!="close") {
                webSocket.send(textMessage.value);
                messagesTextarea.value +=" Send to Server ===> "+ textMessage.value +"\n";
                textMessage.value="";
            }else {
                websocket.close();
            }   
        }
        function processClose(message) {
            webSocket.send("Client disconnected......");
            messagesTextarea.value +="Server Disconnected... "+"\n";
        }
        function processError(message) {
            messagesTextarea.value +=" Error.... \n";
        }
    </script>
    </body>
    </html>

控制器2:

package chat

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/testing")
class TestingController  {

    @OnOpen
    public void handleOpen() {
        System.out.println("Client is now connected.");
    }

    @OnMessage
    public String handleMessage(String message) {

        System.out.println("Client sent: " + message);
        String replyMessage = "echo "+message;
        System.out.println("Send to Client: " + replyMessage);
        return replyMessage;
    }

    @OnClose
    public void handeClose() {
        System.out.println("Client is now disconnected.");
    }

    @OnError
    public void handleError(Throwable t) {
        t.printStackTrace();
    }

}

这与我运行应用程序时一样

我在chrome中遇到以下错误:

WebSocket connection to 'ws://localhost:8080/chat/testing' failed: Error during WebSocket handshake: Unexpected response code: 404 index:37
WebSocket is already in CLOSING or CLOSED state.  

和textArea

Error.... 
Server Disconnected... 
在ggts控制台上我看到了:

Client sent: null
Send to Client: echo null

最初我以这种方式尝试控制器:

package chat


class TestingController extends TestingEndpoint  {

}

并在src / java / chat

package chat;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;


@ServerEndpoint("/testing")
class TestingEndpoint  {

    @OnOpen
    public void handleOpen() { 
        System.out.println("Client is now connected.");
    }
    @OnMessage
    public String handleMessage(String message) {

        System.out.println("Client sent: " + message);
        String replyMessage = "echo "+message;
        System.out.println("Send to Client: " + replyMessage);
        return replyMessage;
    }
    @OnClose
    public void handeClose() { 
        System.out.println("Client is now disconnected.");
    }
    @OnError
    public void handleError(Throwable t) {
        t.printStackTrace();
    }

}

除了ggts控制台

中的任何内容外,此方法产生相同的结果

想知道是否有人让javax.websocket在Grails中工作..

1 个答案:

答案 0 :(得分:1)

确定它正常工作 - 毕竟不是那么糟糕

这是修复:

  1. gsp中的一些拼写错误:
  2. index.gsp中

    <!DOCTYPE html>
    <html>
        <head>
            <meta name="layout" content="main">
            <g:set var="entityName" value="${message(code: 'admin.label', default: 'Admin')}" />
            <title><g:message code="default.create.label" args="[entityName,BAH,BAH]" /></title>
        </head>
        <body>  
        <form>
        <input id="textMessage" type="text">
        <input type="button" value="send" onClick="sendMessage();">
        </form>
        <br>
        <textarea id="messagesTextarea" rows="10" cols="50">
        </textarea>
    
        <script type="text/javascript">
            var webSocket=new WebSocket("ws://localhost:8080/chat/annotated");
            var messagesTextarea=document.getElementById("messagesTextarea");
            webSocket.onopen=function(message) {processOpen(message);};
            webSocket.onmessage=function(message) {processMessage(message);};
            webSocket.onclose=function(message) {processClose(message);};
            webSocket.onerror=function(message) {processError(message);};
            function processOpen(message) {
                messagesTextarea.value +=" Server Connect.... "+"\n";
            }
            function processMessage(message) {
                messagesTextarea.value +=" Receive from Server ===> "+ message.data +"\n";
            }
            function sendMessage() {
    
                if (textMessage.value!="close") {
                    webSocket.send(textMessage.value);
                    messagesTextarea.value +=" Send to Server ===> "+ textMessage.value +"\n";
                    textMessage.value="";
                }else {
                    websocket.close();
                }   
            }
            function processClose(message) {
                webSocket.send("Client disconnected......");
                messagesTextarea.value +="Server Disconnected... "+"\n";
            }
            function processError(message) {
                messagesTextarea.value +=" Error.... \n";
            }
        </script>
        </body>
        </html>
    

    现在是终点的实际修复,我从这里偶然发现了它: https://tyrus.java.net/documentation/1.7/index/deployment.html 例3.2。使用ServerContainer部署带注释的端点

    所以修复是添加src / java / MyServletContextListenerAnnotated.java

    package chat;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    import javax.websocket.DeploymentException;
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.server.ServerContainer;
    import javax.websocket.server.ServerEndpoint;
    
    
    
    @WebListener
    @ServerEndpoint("/annotated")
    public class MyServletContextListenerAnnotated implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            final ServerContainer serverContainer = (ServerContainer) servletContextEvent.getServletContext()
                                                        .getAttribute("javax.websocket.server.ServerContainer");
    
            try {
                serverContainer.addEndpoint(MyServletContextListenerAnnotated.class);
            } catch (DeploymentException e) {
                e.printStackTrace();
            }
        }
    
       /* @OnMessage
        public String onMessage(String message) {
            return message;
        }
    */
        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
        }
        @OnOpen
        public void handleOpen() { 
            System.out.println("Client is now connected.");
        }
        @OnMessage
        public String handleMessage(String message) {
    
            System.out.println("Client sent: " + message);
            String replyMessage = "echo "+message;
            System.out.println("Send to Client: " + replyMessage);
            return replyMessage;
        }
        @OnClose
        public void handeClose() { 
            System.out.println("Client is now disconnected.");
        }
        @OnError
        public void handleError(Throwable t) {
            t.printStackTrace();
        }
    }
    

    由于gsp中的端点已更新为使用新端点,因此最后一步是将_Events.groovy添加到脚本中:

    import groovy.xml.StreamingMarkupBuilder
    
    eventWebXmlEnd = {String tmpfile ->
        def root = new XmlSlurper().parse(webXmlFile)
        root.appendNode {
           'listener' {
               'listener-class' (
                   'chat.MyServletContextListenerAnnotated'
               )
            }
        }
    
        webXmlFile.text = new StreamingMarkupBuilder().bind {
            mkp.declareNamespace(
                    "": "http://java.sun.com/xml/ns/javaee")
            mkp.yield(root)
        }
    }
    

    和booom那里 - 服务器连接客户端发送等等