The Java / JavaScript Socket Bridge
Please note: This software is long out of date, and I'm afraid I do not have the time to update it. I am leaving this page here as a reference because of the project's popularity. Please do not contact me about this project.
A more recent fork of this project is now on GitHub thanks to Ian Hilt.
Use real sockets in JavaScript via a simple, invisible Java applet.
About
Sometimes AJAX is simply not enough. Sometimes you need the capability to use real sockets in JavaScript. That's what this project is here for: by including this simple applet in an HTML page, you can use Java sockets via a few simple JavaScript functions. This is not an original idea by any means, but all the other attempts I have seen to create something like this do not work or get bogged down in security problems. So I made my own. It works in Java 6, despite the new security stuff, assuming you accept the certificate.
See It in Action
Check out this simple example. Pressing the "Run!" button establishes a connection to google.com on port 80 and sends a nonsense request. It then gets the response text and displays it on the page (don't worry, it's supposed to be an error). View the page source to see how elegant the code is.
Download
Here. Source code is included in case you want to see how it works or need to compile it yourself.
How To Use It
Include the JavaScript functions in the head of your HTML document:
<script type="text/javascript" src="java_socket_bridge.js"></script>
Include the Java applet in the body of your HTML document:
<applet id="JavaSocketBridge" archive="JavaSocketBridge.jar" code="JavaSocketBridge.class" width="0" height="0"> </applet>
Now you should have the following functions available to you in JavaScript:
socket_connect(url, port)
Connect to a given url (string) on a given port (integer). Returns true or false depending on success.
socket_disconnect()
Disconnect the current socket. Returns true or false depending on success.
socket_send(message)
Send a string over the socket. Returns true or false depending on success.
on_socket_get(message)
This method is called by the applet every time something comes over the socket from the server. It is blank by default, so overwrite it to handle input.
on_socket_error(message)
This method is called by the applet every time an error crops up. It alerts you with the error description by default, so overwrite it to handle errors.