Search code examples
javagoogle-app-enginechannel-api

Google Channel API message from JavaScript client to server


After a while I got the first part of the Google Channel API working. Now I have some problems with sending a message from the JavaScript client to the server. Here is the servlet for the Google Channel API connection:

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (user != null) {
        ChannelService channelService = ChannelServiceFactory.getChannelService();
        String token = channelService.createChannel(user.getUserId());

        FileReader reader = new FileReader("index.html");
        CharBuffer buffer = CharBuffer.allocate(16384);
        reader.read(buffer);
        reader.close();

        String index = new String(buffer.array());
        index = index.replaceAll("\\{\\{ token \\}\\}", token);

        resp.setContentType("text/html");
        resp.getWriter().write(index);
    } else {
        resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
    }

The index.html looks like following:

<script src="/_ah/channel/jsapi"></script>

<body>
    <script type="text/javascript">
        onOpened = function() {
            alert("opened");
        }

        var token = "{{ token }}";
        var channel = new goog.appengine.Channel(token);
        var handler = {
            'onopen' : onOpened,
            'onmessage' : onMessage,
            'onerror' : function() {
            },
            'onclose' : function() {
            }
        };
        var socket = channel.open(handler);
        socket.onopen = onOpened;
        socket.onmessage = onMessage;

        function sendMessage() {
            // Send JSON object to server   
        }
    </script>
    <h1>Google Test Channel API</h1>
    <form>
        <input type="button" value="Send" onclick="sendMessage();">
    </form>
</body>

If I load the application I get the opened alert, I believe the connection is working. Now I would like to send a message to the server, if someone clicks on the button.

I read that I have to use the XMLHttpRequest function with POST or GET. But I won’t pass a new url, I would just pass a value. Is there a way to send a JSON object to the server?

Something like:

{
    "message": "This is a JavaClient message!"
}

Solution

  • This doesn't really have much to do with the Chanel API - it's just a standard xhr call back to the server. You can use standard code like this, or use a library such as jquery like this.

    If you need to parse javascript into JSON use JSON.stringify().

    At the server you can process your request as required, send a response back to the client via standard HTTP or use the Chanel API to send a message not just to the original client, but to all connected clients.