Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TriremeServlet Node js import external websocket libraries #177

Open
kthyagaraj opened this issue Feb 9, 2018 · 3 comments
Open

TriremeServlet Node js import external websocket libraries #177

kthyagaraj opened this issue Feb 9, 2018 · 3 comments

Comments

@kthyagaraj
Copy link

kthyagaraj commented Feb 9, 2018

Apologies if this is not the right place to ask question, i wouldn't find any other option or forum online who can assist me on this.

I am using trireme servlet to run the node js script in my application. i have added all the maven dependencies and the deployment description looks as below

<servlet>
   <servlet-name>TriremeServlet</servlet-name>
   <servlet-class>io.apigee.trireme.servlet.TriremeServlet</servlet-class>
   <init-param>
     <param-name>TriremeScript</param-name>
     <param-value>/WEB-INF/node/server.js</param-value>
   </init-param>
   <init-param>
     <param-name>TriremeResponseTimeout</param-name>
     <param-value>5</param-value>
   </init-param>
   <init-param>
     <param-name>TriremeStartupTimeout</param-name>
     <param-value>30</param-value>
   </init-param>
   <init-param>
     <param-name>TriremeSandbox</param-name>
     <param-value>false</param-value>
   </init-param>
 </servlet>
 <servlet-mapping>
   <servlet-name>TriremeServlet</servlet-name>
   <url-pattern>/servlet/*</url-pattern>
 </servlet-mapping>

And my server.js script is below the path /WEB-INF/node/server.js

var fs = require('fs');
var http = require('http');
var path = require('path');
var util = require('util');

....
var server = http.createServer(handleRequest);

server.listen(PORT, function() {
    console.log('Listening on %d', PORT);
});

The above code works fine , i would like to import external libraries to my server.js , added the websocket js files in the same dir /WEB-INF/node/, and tried to import as below. now the script is failing while i try to access the servlet, no errors on log..

var websocket = require('./websocket.js');
Is this the rightway to include the external libraries for the node script that is run by trireme servlet ... appreciate if any feedback

@gbrail
Copy link
Contributor

gbrail commented Feb 13, 2018

This is a fine place to ask -- thanks!

It's been a while, but looking at TriremeServlet.java, I see that it calls:

ServletConfig.getServletContext().getRealPath("/")

to find the location of your script. Since "websocket.js" is in the same directory as server.js, then yes, your require statement should work without having trouble finding the module, as normal Node.js module resolution should apply and Trireme will use the Node.js "modules" module.

You could try two things:

First, does a very basic script load? I'm asking because "websocket.js," if it's the module I'm thinking of, won't work in Trireme anyway because it depends on a bunch of native stuff that Trireme doesn't support. It'd be great to test your script outside the servlet module first. The NPM module is a great place to start:

https://www.npmjs.com/package/trireme

Second, you can try putting the required code elsewhere, and setting NODE_PATH to find it, as you would for any other Node app:

https://nodejs.org/docs/latest-v0.10.x/api/modules.html

However in that case you'd use "require('websocket')" instead to load it.

@kthyagaraj
Copy link
Author

kthyagaraj commented Feb 14, 2018

thanks for your response, i was able to solve the problem, actually i was using the node module
https://github.com/websockets/ws (this package was not working with trireme servlet).
Have no idea wht's happening with the /ws modules, any guess why its not working ?

Later i switched to another package
https://github.com/theturtle32/WebSocket-Node (this worked), i was able to do require(websocket) in my server.js

Now i am coming to second part of my implementation where i am stuck, just posting here if you can help me on this or suggest any

I have the server.js now running the websocket server on http. the code is below

var fs = require('fs');
var http = require('http');
var path = require('path');
var util = require('util');
var url = require('url');
var HashMap = require('hashmap');
var WebSocketServer = require('websocket').server;

var PORT = 33333;

var userConns = new HashMap();

var counter = 0;

function handleRequest(req, resp) {
    console.log('websocketservlet handleRequest: %s %s', req.method, req.url);

    if (/[^/]*\/websocketservlet\/newpatient.*$/.test(req.url)) {
        newPatient(req, resp);
    } else {
        resp.writeHead(404);
        resp.end();
    }
}

function newPatient(req, resp) {
    var q = url.parse(req.url, true).query;
    var userId = q.USER_ID;
    var patientName = q.PATIENT_NAME;
    var redirectUrl = q.REDIRECT_URL;
    console.log('websocketservlet newPatient: userID=' + userId + ' patientName=' + patientName + ' redirect=' + redirectUrl);

    // Websocket notification(s).
    if (userId) {
        var userConn = userConns.get(userId);
        if (userConn) {
            console.log('websocketservlet Sending data from Cached Connection object for userId : ' + userId);
            userConn.sendUTF(userId + "|" + patientName);
            console.log('websocketservlet Sent data from Cached Connection object for userId : ' + userId);
        } else {
            console.log('websocketservlet Cached Connection object not available for userId : ' + userId);
        }
    } else {
        console.log('websocketservlet userId not valid : ' + userId);
    }

    resp.writeHead(302, {
        Location: '/easycare' + redirectUrl
    });
    resp.end();
}

var server = http.createServer(handleRequest);
server.listen(PORT, function() {
    console.log('websocketservlet started.');
});

var wsServer = new WebSocketServer({
    httpServer: server
});

wsServer.on('request', function(request) {
    var connection = request.accept('user-notification', request.origin);
    console.log((new Date()) + ' Connection accepted. ' + connection);
    connection.on('message', function(message) {
        console.log('websocketservlet Received userId from client : ' + message.utf8Data);
        userConns.set(message.utf8Data, connection);
        console.log('websocketservlet connection cached for userId ' + message.utf8Data);
    });
    connection.on('close', function(reasonCode, description) {
        console.log('websocketservlet ' + (new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

And my web.xml looks as mentioned previously and i am starting the servlet onstartup, when the server is up, so i have trireme servlet loading the server.js with websocket connection ready to use.

Now from my application client javascript i want to establish connection with the websocket and send and recieve messages for users. I am not able to establish connection with the websocket running on 33333
`` socket = new WebSocket('ws://localhost:33333/');
`
if i run the above websocket server and client as standalone node scripts , they all work fine, but i want that to be part of the application where i have necessity to use the trireme servlet.

i am running the servlet inside my application which is hosted on a Jboss server on port 8080, not sure what is the right approach i can do to establish a connection with websocket running inside a script which is called by trireme servlet , if any suggestions pl provide

@gbrail
Copy link
Contributor

gbrail commented Feb 14, 2018 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants