Java and JavaScript WebSockets

Java WebSockets Made Simple With Example

October 12, 2016


Quick Access:

What A WebSocket Is And Why You Should Use It

A Simple Explanation of WebSockets

A websocket is an open connection that can send and recieve data from client to server (or vice versa) in real time. Much like AJAX, it can create, update, delete data on a web page without having to reload it, however, with websockets your connection stays open for however long you wish.

Why Should You Use WebSockets

Since you have the ability to manipulate data instantly in real-time, there are quite a few interesting applications that you can create where time-sensitivity is a factor. Some of these applications could be in video games such as a mutliplayer shooter, stock market analysis, or even chat messaging.

A Simple WebSocket Example Using Java Server-side and JavaScript Client-side

Note: Since there must be communication between the client and server side, you need to actually run your application on a server such as Tomcat, WildFly, JBoss, etc. Also, all socket code will be within script tags on the client side since it IS JavaScript.

Using a WebSocket Client-side With JavaScript

JavaScript WebSocket Overview:

1) Create a WebSocket Object – establishes a new JavaScript websocket object with a connection designated towards the server-side websocket.

2) Create ‘onopen’ function – This function is what sends data to the server-side websocket. In our example, it is a user-inputted name.

3) Create ‘onmessage’ function – This function recieves data from the server-side websocket and does something with that data.

Create A JavaScript WebSocket Object

0a) Set a new variable to a websocket uri. This line is how the websocket knows which server-side websocket to communicate with, so it is VERY IMPORTANT to double-check that the websocket name at the end of this uri is the same as the websocket name of the server websocket want to work with.

The URI consists of 5 pieces:

i) “ws://” or “wss://” for secured connections – websockets work off of HTTP UPGRADE and by replacing the ‘http’ or ‘https’ with the ‘ws’ or ‘wss’ we are enabling this HTTP UPGRADE status. It’s a bit technical and you could probably read more about it, but for someone who just needs the code to work right now, just know the ‘ws’ or ‘wss’ is what enables websockets to work.

ii) localhost – to run on your own computer’s network

iii) 8080 – the port number that are using to run your web application. This number can change, for example with those that already have that port number in use, so you can change it, however, it will most often stay the same.

iv) The name of your web application or project – for this example, the name of the project is ‘WebSocketExample’.

v) The name of the server-side websocket your want to communicate with. In this example, we want to communicate back and forth with ‘aWebSocketname’

a) var wsUri = "ws://localhost:8080/WebSocketExample/aWebSocketName";

b) Create a new websocket object with the websocket uri variable create in step a.

b) var newWebSocket = new WebSocket(wsUri);

Create the JavaScript WebSocket’s ‘onopen’ Function

a) Start the ‘onopen’ websocket function – This function is what will send designated data to the server web socket.

a) newWebSocket.onopen = function (randomParam) {

b) Create a variable to hold a string value, such as your name. I used mine for this example.

b) var dataToSendToJavaWebSocket = "Weston";

c) Send the data – now we will send the data by using our websocket object’s send function and placing in the string variable (Weston) inside as a parameter.

c) newWebSocket.send(dataToSendToJavaWebSocket)  };

Create the ‘onmessage’ JavaScript WebSocket function

a) Starting the ‘onmessage’ function – We’ll start the function by getting our JavaScript websocket object and its onmessage property, then setting it to a new function with a parameter. The parameter is a reference to the data recieved from the Java websocket server endpoint. Once we are working inside the function, we will be able to reference this data using that parameter name.

a) newWebSocket.onmessage = function (dataFromJavaWebSocket) {

b) Set the Java websocket data to a variable. Create a new variable and set it to the reference name from the onmessage function’s parameter and then add a ‘.data’.

b) var data = dataFromJavaWebSocket.data;

c) Append the data to a div so we can see it on-screen. Now, we’ll just grab a reference to a div that lives in the body of the html file by using its id. Make sure it is in quotes and has a ‘#’ or it will not work. Next, use the JQuery ‘append’ method to add in some html code. Any html code within this append method should be surrounded in quotes. For the JavaScript data variable that we previously created, we’ll concatenate it to our html string.

c) $("#dataFromSocketContainer").append("
<h2>"+data+"</h2>
");

d) Now, we can close the websocket since we no longer have a need for the connection. To do this, call the websocket function ‘close’.

d) newWebSocket.close();  };

Here’s the full JavaScript WebSocket code:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web Socket JavaScript Echo Client</title>
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
  
 
  //WEB SOCKET FUNCTION THAT GETS CALLED FROM CLIENT SOMEWHERE IN ITS CODE
  function fireWebSocketCode() {
      
      //CREATE A NEW WEBSOCKET
	  var wsUri = "ws://localhost:8080/WebSocketExample/aWebSocketName";
	  var newWebSocket = new WebSocket(wsUri);
      
      //GET DESIRED DATA FROM CLIENT-SIDE, THEN SEND TO JAVA WEBSOCKET
      newWebSocket.onopen = function (randomParam) {
      	var dataToSendToJavaWebSocket = "Weston";
      	newWebSocket.send(dataToSendToJavaWebSocket);
      };
      
      //RECIEVES DATA FROM JAVA WEBSOCKET AND UPDATES CLIENT-SIDE
      newWebSocket.onmessage = function (dataFromJavaWebSocket) {
      	var data = dataFromJavaWebSocket.data;
      	//DO SOMETHING WITH VAR DATA
      	$("#dataFromSocketContainer").append("<h2>"+data+"</h2>");
      	newWebSocket.close();
      };
      
      //RUN CODE IF WEBSOCKET HAS AN ERROR WHILE RUNNING
      newWebSocket.onerror = function (evt) {
      	newWebSocket.close();
      }; 
      
  }
  
</script>
</head>
<body>
	<button type="button" onclick="fireWebSocketCode()">Show User From WebSocket</button>
	<div id="dataFromSocketContainer">
	</div>
</body>
</html>

Recieving and Sending Data Through a Java Server-side WebSocket

Java WebSocket Overview
1) ServerEndpoint Annotation – helps the JavaScript websocket where it is communicating
2) OnMessage Annotation – the designated method that does something with the string variable it recieves.

Setting up the Java WebSocket Class

a) Create a new Java class – this example’s class name is AWebSocket Name
b) Add the ‘@ServerEndpoint’ annotation – After your class has been created, add the websocket annotation ‘@ServerEndpoint” with a parameter. This parameter will represent the url that the JavaScript websocket will point to when it is looking for a server websocket to communicate with. It’s simply a forward slash ‘/’ and the name.

b) @ServerEndpoint("/aWebSocketName")
   public class AWebSocketName
   {

c) Create a new method that will return a String, has a String parameter and an ‘@OnMessage’ annotation.
i) Since the JavaScript websocket will be expecting a string in return of its request, then we have to make sure that this method will return a String.
ii) This method needs a String parameter because it is the method that will do something with the string data that was sent from the JavaScript websocket and this parameter represents that data.
ii) The name of the this new method can be named absolutely whatever you wish, the only caveat is that it must be designated with the ‘@OnMessage’ annotation. This annotation lets the Java websocket class know where and what to do with the incoming and outgoing string data. Without this annotation above this new class, you will see a flurry of errors running across your servers logger.

c) @OnMessage
	public String doSomethingWithClientRequest(String stringFromClientSideSocket)
	{

d) Doing something with the String data parameter – Now that we have our ‘OnMessage’ method set, we can start to do something with the data that it recieves. Create a new String variable and set it to the String parameter value.

d) String data = stringFromClientSideSocket;

e) Returning String Data to the JavaScript WebSocket – To send back String data to the JavaScript websocket we will use the return method with a custom String value that has the previously created String variable in it. This will complete the ‘OnMessage’ function requirements and then send back the custom String data to the JavaScript websocket’s ‘onmessage’ function.

e) return "Hello "+data+", you just successfully used a websocket.";

Here’s the full code:

import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/aWebSocketName")
public class AWebSocketName
{

@OnMessage
public String doSomethingWithClientRequest(String stringFromClientSideSocket)
{
String data = stringFromClientSideSocket;

return "Hello "+data+", you just successfully used a websocket.";
}
}

That wraps up this Java WebSockets Made Simple With Example tutorial! Happy Coding!