简体   繁体   中英

Socket Communication between Java server on client and Javascript

I want to establish a socket communication between javascript running on a web page and a java SocketServer running on my client machine so that as soon as the connection is established between the two, an excel sheet is opened on the client machine. I know that it would cause security issues, but since the communication would be on localhost so I am Ok with that.

Here is my java server running on client:

import java.io.*;
import java.net.*;

public class ServerExcelOpenOnJavaScriptConnect {
    public static void main(String args[]) throws Exception {
        ServerSocket welcomeSocket = new ServerSocket(12345);


            Socket connectionSocket = welcomeSocket.accept();
            Process p =
                    Runtime.getRuntime()
                            .exec("C:\\Program Files (x86)\\Microsoft Office\\Office14\\excel.exe c:\\users\\rahulserver\\desktop\\abcd.xlsx");
            System.out.println("Waiting for excel file ...");
            p.waitFor();
            System.out.println("Excel file done.");

            //Runtime.getRuntime().exec();

    }
}

Here is my html with javascript:

    <html>
<head>
    <title>TCP Socket test</title>
    <script type="text/javascript">
    function connect(){
                var host = 'localhost';
                var port = 12345;
        var socket = new io.Socket('localhost',{'port':12345});
        socket.connect();
        alert("connected");
}



    </script>
</head>

<body>
    <button onclick="connect()">Connect</button>
</body>
</html>

The connection is not getting established as the server keeps on waiting for connection on port 12345. So how should it be done?

You're kind of on a dirt road and you need to get yourself on a freeway.

javascript can communicate to java code in the specific case where the browser got the web page and javascript from a host and then the javascript connects back to that same host to get a connection for more data.

In your case, you'd like the same machine to be both client and server. But it is easier to understand what's required if you realize this idea of two machines: a client running the browser and the server which runs java.

So, you can find many examples of this on the web. For example, take a look at java running in Tomcat, providing a web page and javascript and then the javascript reading json data using a different URL on the Tomcat server.

If you think of the main-stream uses of web technology you can find videos demonstrating what you'd like to see. Look around, for example, at the AngularJS demos and RESTful Web Services demos.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM