I am teaching a Java course. Instead of teaching the Java GUI libraries (awt or swing), I want to teach my students to use HTML for GUI, and use Java only in the server side. So, I want to build a Java server and an HTML page that connect to each other using sockets. I want to use only raw Java, so that my students do not have to install third-party libraries. So far, I built the following Java server, which just accepts strings and reverses them:
import java.io.*;
import java.net.*;
public class ReversingServer {
public static void main(String[] args) throws Exception {
int port = 8005;
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
final Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String input = reader.readLine();
System.out.println("input="+input);
String output = (input==null?
null:
new StringBuilder(input).reverse().toString());
writer.println("The reverse of "+input+" is ... ");
writer.println("... "+output+"!");
writer.close();
}
}
}
When I run this application, I can do "telnet localhost 8005" and send a string such as "abc" and get the response "the reverse of abc is cba".
I also started building the HTML GUI:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test the Reversing Server</title>
</head>
<body>
<div>
Enter a string to reverse:
<input name="input"></input>
<input type="submit"></input>
</div>
<div id='response' style='border:solid 1pt black'>
</div>
</body>
</html>
But here I am stuck - how do I make the HTML page connect to the Java server?