Embed Websockets in my Tomcat Servlet?

I am trying to use websockets in an already running servlet. My problem is that I used the "writer" class to send HTML to broswer, but I cannot 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 publish everything, but Servlet basically creates a form where I can enter the path to the TXT file. Then the txt file will be sorted using 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 to get you started will help me a lot. Thanks in advance.

+6
source share
2 answers

Firstly, if you want to work with websockets from tomcat, you must go from the corresponding base class WebSocketServlet.

Secondly, I do not think that it is worth using websocket in your case. Websockets are good for applications requiring real-time interaction. Yours obviously does not require this.

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

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

But, as I said, I do not see the point in such a code.

+3
source

Before moving from a regular servlet to a websocket, there are a few things to keep in mind.

  • Use the latest version of Tomcat Apache. The Plder version does not support web ports. (I used version 7.0.42 in my case)
  • You cannot just replace your servlet with WebSocket. The goal of both is completely different. Google is for more details.

This sample code for WebSocket provides the server side as well as sample client-side code. You must forward it to begin.

0
source

Source: https://habr.com/ru/post/925571/


All Articles