Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Websockets into my Tomcat Servlet?

Iam trying to use websockets in my already working servlet. My Problem is that i used the "writer" class to post HTML onto the broswer but I cant find a similar class for WebSockets.

My servlet looks like this:

@WebServlet("/TestServlet")

public class TestServlet extends HttpServlet {
private List<ISort> sortierListe = new ArrayList<ISort>();
private File file1;
private PrintWriter writer2;
private boolean sortFinished;
boolean bSubmitForFilenamePressedCopy;
BufferedReader in;
// private String sEingabe;
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public TestServlet() {
    super();    
    this.initSortierverfahren();
}

private void initSortierverfahren() {
    sortierListe.add(new BubbleSort());
    sortierListe.add(new QuickSort());
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

[...]

PrintWriter writer = response.getWriter();
    writer2 = writer;
    writer.println("<html>");
    writer.println("<head><title>Text Sortieren!</title>");
    writer.println("</head>");

    writer.println("<body marginwidth='40' leftmargin='40' bgcolor='#E5E5E5'>");

    writer.println("<table bgcolor='#FFFFFF' height='100%' width='57%' border='0' cellpadding=10>");
    writer.println("<tr height='10%'>");
    writer.println("
[...]

The code is too long to post everything, but the Servlet basicly creates a form where I can enter a path to a .txt file. The txt file will then be sorted by either bubblesort or quicksort.

My Question is: How can I use this code in a WebSocket without rewriting everything in javascript? Just some basic help for the start would help me alot I think. Thanks in advance.

like image 710
registaid Avatar asked Sep 17 '12 12:09

registaid


1 Answers

First, If you want to work with websockets from tomcat, you should extend from corresponding base class WebSocketServlet.

Second, I don't think that it's worth using websocket in your case. Websockets are good for applications which require real-time interactions. Yours obviously doesn't require it.

If you still want to do this, just create some simple javascript which will write your html to the body. Something along lines with:

websocket = new WebSocket(wsUri); 
websocket.onmessage = function(evt) { 
  document.body.innerHtml += evt.data
};

But as I said, I see no use in such a code.

like image 160
Konstantin Solomatov Avatar answered Oct 04 '22 03:10

Konstantin Solomatov