hachi__man
hachi__man

Reputation: 1

socket connection in servlet class

I am trying to establish a tcp connection through which I want to share data from one webform(jsp page) to another web page with same content.

below is servlet which gets called when clicking button on jsp page. As I checked the port which trying to connect is in listening state and from servlet it should get redirected to receiver form but it just keeps loading.

but program is getting stuck at Socket insocket = socket.accept(); this line. I searched in other resources as well but got answer as "Socket.accept() hangs by design until a client connects to the port that is being waited on, in this case, port 8189. Your program is working fine"

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String first = request.getParameter("first_name");
        String last = request.getParameter("last_name");
        String name = first + " " + last;
        PrintWriter out = response.getWriter();
        byte buffer[] = new byte[10240];
        buffer = name.getBytes();
        try {
            ServerSocket socket = new ServerSocket(4333);
            Socket insocket = socket.accept();
            OutputStream outSocket = insocket.getOutputStream();
            outSocket.write(buffer);

            response.sendRedirect("receiver.jsp");
        } catch (java.net.ConnectException e) {
            System.out.println("server application not started.....");
        }

    }


Upvotes: 0

Views: 215

Answers (1)

Stephen C
Stephen C

Reputation: 718798

The recommended way to establish a socket-like connection between a web browser or client and a web server is to use WebSockets. This causes the connection used for the HTTP request / response to be taken over for bidirectional socket communication. It is a widely supported extension to the HTTP protocol.

If you want to connect two or more web browsers or web clients via the web server, you need to establish WebSockets between each browser server, and then the server needs to route the information from between the server ends of the WebSockets.

The implementation details will depend on the technology stack used on the client and server sides. You could start by reading the following:


They way you are trying to do it looks like it won't work. Even if it does kind of work, there will be issues with managing the connections that you have established ... leading to resource leakage, problems with recycling ports, etcetera. And then you need to deal with potential security issues; e.g. establishing that the client that connects to the ServerSocket port you are listening on is not some interloper.

Upvotes: 1

Related Questions