0

I have one index.jsp file, one connect.java servlet and one Server.java file which creates a chat server.

index.jsp

<form action="connect">
    <textarea name="chat-window" ></textarea>
    <input name="port-number" placeholder="enter-port"/>
    <select name="action-type">
        <option> start </option>
        <option> stop </option>
        <option> refresh </option>
    </select>
    <button name="apply-btn" type="submit"> apply </button>
</form>

connect servlet

// creates new thread(runnable) to run Server.java and 
// passes portNumber, printWriter object generated by response.getWriter() to Server.java

Server.java

// creates serverSocket on portNumber
try {
    serverSocket = new ServerSocket(portNumber); 
} catch (IOException e) {
    showException("Server.startRunning(): new ServerSocket() ", e);
}

printWriter.println("Server is online at " + portNumber + " \n");

It prints Server is online at XXXX

But, after this, i think printWriter becomes unusable, maybe entire link of index.jsp page to threaded Server.java object gets broken. Because, form action="connect" is completely performed and server is started and it doesn't wait for clients to get connected.

now, if i add following to Server.java

while(true) {
    try {
        clientSocket = serverSocket.accept();
        printWriter.println("Client Connected.");
        // JOptionPane.showMessageDialog("Client Connected.", null);
    } catch() {
        // Exception handling mechanism
    }
}

and if, now, client connects to Server, printWriter statement doesn't print anything (maybe because the actual web-page needs to be refreshed, but why? how can i make it dynamic if this is the problem? ).

I can verify that client gets connected successfully because if i uncomment the JOptionPane statement, it shows when a client gets connected. So, no issues on client-side.

How can i make the printWriter statement work? Somehow, keep the connection between JSP and Server.java alive. Make the Servlet/JSP continuously listen to Server.java

index.jsp view index.jsp

connect.java servlet view connect.java

  1. I didn't have a perfect title for this question.
  2. If this is impossible, kindly write an alternative.
rupinderjeet
  • 2,984
  • 30
  • 54
  • I expanded it into an answer. – BalusC Jun 16 '16 at 09:41
  • 1
    You think the `PrintWriter` becomes unusable *why*? NB Don't write code like this. Code that depends on the success of code in a prior `try` block should be inside that `try` block. At present your code is perfectly capable of printing `Server is online` when it isn't, for example. – user207421 Jun 16 '16 at 09:42
  • I want to know the reason of downvote. There was no code format issues, i did explain everything, i supplied code, there's no duplicates. I was just short on the knowledge. I guess no one is perfect. Down voters should post the reason. – rupinderjeet Jun 16 '16 at 10:08
  • @EJP: you are right. but, if serverSocket initialization fails, it will print Exception First, and then say 'Server is online'. anyway, i took your advice. – rupinderjeet Jun 16 '16 at 10:10
  • The reason for my downvote was that you haven't provided any evidence of the actual problem, and you still haven't done so even after I asked for it, – user207421 Jun 16 '16 at 23:39
  • I already wrote that PrintWriter passed as a parameter/arguement becomes unusable because somehow link between Server.java Thread and Servlet gets broken, which is due to the fact that all the code execution is completed. Jsp did its part. Servlet ran the thread. Thats it. Nothing beyond that is web related. – rupinderjeet Jun 17 '16 at 10:02
  • And, for proof of actual problem, the printWriter didnt work after client connected to the server. IDK but if I was in the wrong, I dont think SO is about asking help. I wrote all of it in question too. It took me an hour to explain my problem there. Please read there. – rupinderjeet Jun 17 '16 at 10:09

1 Answers1

1

Don't do that. Passing around HTTP request/response related state to a different thread outside the HTTP thread is recipe for disaster. Once the servlet doXxx() method returns, then the request/response objects and all of its related state are garbaged (simply because they're finished doing their HTTP based job) and become unusable (so any attempt to use them anyway would only result in unexpected behavior or exceptions like IllegalStateException). Never do that.

As to your concrete functional requirement of opening a persistent two-way client-server socket connection, you seem to be confusing desktop applications with web applications while searching for solutions. The code which you've there would only work for desktop applications. For web applications, you need web sockets instead. Use JavaScript's window.WebSocket API in client side (tutorial here) and Java EE's javax.websocket API (JSR356) in server side (tutorial here).

Do note that this API is very low level, it's nearly as low level as HTTP. For instance, in the Servlet API you have "session" scope ready for direct use and you can easily identify users and all, but in WebSocket API not. You have to (re)invent and code all the scopes/layers yourself. If you can, rather go for an existing library/framework. For example, Java EE's own MVC framework JSF has several libraries (plugins) available for the job, such as OmniFaces <o:socket> tag which is demonstrated here (and developed by yours truly).

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • This is so hard already. The only reason i started learning JSP & Servlet last week was because i found out that you can't run direct java-file code on actual server(like godaddy) without hack-slashing or costy methods. and now, i have to use JSF and Omnifaces about which i don't have a clue. I just wanted to have a online server and make android app clients connecting to it. Nothing is difficult for me to learn, but i feel like i am trying to swallow all of languages, be it java, android or php – rupinderjeet Jun 16 '16 at 10:05
  • [One bite at a time](http://stackoverflow.com/q/1958808). You can of course also write all code yourself using low-level JSP/Servlet/WebSocket instead of using already-written code from frameworks/libraries. It's only going to take a bit longer in the end. – BalusC Jun 16 '16 at 10:06