How to Implement a Java WebSocket Server for Image Transmission with Jetty

In the previous articles, I shared how to implement a .Net WebSocket server with SuperWebSocket. Today, I’d like to continue the series WebSocket: How-to, talking about how to implement a WebSocket server in Java.

What is Jetty?

“Jetty provides a Web server andjavax.servlet container, plus support forSPDY, WebSocket, OSGi, JMX, JNDI, JAASand many other integrations.” from http://www.eclipse.org/jetty/

Quickly Setup a Java WebSocket Server

Create a class WSHandler which extends the class WebSocketHandler:

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

@WebSocket
public class WSHandler extends WebSocketHandler {

    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
    }

    @OnWebSocketError
    public void onError(Throwable t) {
    }

    @OnWebSocketConnect
    public void onConnect(Session session) {
    }

    @OnWebSocketMessage
    public void onMessage(String message) {
    }

	@Override
	public void configure(WebSocketServletFactory factory) {
		// TODO Auto-generated method stub
		factory.register(WSHandler.class);
	}
}

Start the server with a port and a handler:

    public static void main(String[] args) throws Exception {
        Server server = new Server(2014);
        server.setHandler(new WSHandler());
        server.setStopTimeout(0);
        server.start();
        server.join();
    }

Done.

JavaScript Client for WebSocket Connection

We can create a simple web client for testing.

Index.htm:

<!DOCTYPE html>
<html>
    <body>
        <script src="websocket.js"></script>
    </body>
</html>

Websocket.js:

var ws = new WebSocket("ws://127.0.0.1:2014/");

ws.onopen = function() {
    alert("Opened");
    ws.send("I'm client");
};

ws.onmessage = function (evt) { 
};

ws.onclose = function() {
    alert("Closed");
};

ws.onerror = function(err) {
    alert("Error: " + err);
};

Run the app and check the message.

Image Transmission Between WebSocket Server & Web Clients

What I’m going to do: Read more

How to Check Alexa Rank in Java

Since we have known how to check PageRank in Java, let’s strengthen our tool by adding the functionality of checking Alexa rank today.

To get the Alexa rank, you can use following code or read the excellent tutorial.

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AlexaRank {

	public static int getAlexaRank(String domain) {

		int result = 0;

		String url = "http://data.alexa.com/data?cli=10&url=" + domain;

		try {

			URLConnection conn = new URL(url).openConnection();
			InputStream is = conn.getInputStream();

			DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document doc = dBuilder.parse(is);

			Element element = doc.getDocumentElement();

			NodeList nodeList = element.getElementsByTagName("POPULARITY");
			if (nodeList.getLength() > 0) {
				Element elementAttribute = (Element) nodeList.item(0);
				String ranking = elementAttribute.getAttribute("TEXT");
				if(!"".equals(ranking)){
					result = Integer.valueOf(ranking);
				}
			}

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return result;
	}
}

Now, let’s update our Java code to write Alexa rank to Excel files.

public void getPageRankAndAlexaRank() {
		// TODO Auto-generated method stub		
		try {
			InputStream excelFile = new FileInputStream(mFileName);
			XSSFWorkbook wb = new XSSFWorkbook(excelFile);
			XSSFSheet sheet = wb.getSheetAt(0);
			XSSFRow row;
			XSSFCell cellPR, cellAR;

			Iterator<Row> rows = sheet.rowIterator();

			int col = 0, colPR = 1, colAR = 2;
			int pageRank = 0, alexaRank = 0;
			String url = null;
			String log = null;

			while (rows.hasNext()) {
				row = (XSSFRow) rows.next();
				url = row.getCell(col).getStringCellValue();
				if (url.matches(Utils.REGEX)) { // check whether URL is valid
					System.out.println(url);
					pageRank = PageRank.get(url); // check page rank
					alexaRank = AlexaRank.getAlexaRank(url); // get alexa rank

					// write PageRank to excel
					cellPR = row.createCell(colPR);
					cellPR.setCellValue(pageRank);

					cellAR = row.createCell(colAR);
					cellAR.setCellValue(alexaRank);

					log = "PR = " + pageRank + ", AR = " + alexaRank;
					if (mEventListener != null) {
						mEventListener.log(log);
					}
					System.out.println(log);
				}
				else {
					System.out.println("URL not valid");
				}

				System.out.println("--------------------------");
			}

			FileOutputStream out = new FileOutputStream(mFileName);
	        wb.write(out);
	        out.flush();
	        out.close();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

Download the updated source package here. Please feel free to contact me at {desmond at dynamsoft dot com} if you have any question.

How to Read and Write Excel Files in Java

Previously, I talked about how to check PageRank in Java. In this article, I will combine PageRank with Excel files. To operate Excel files in Java, I used Apache POI – the Java API for Microsoft Documents. Apparently, you can download the API package, and follow the relevant tutorials to learn how to use POI. When I first downloaded the Java library, I was astonished by how many jar files there were. I had no idea which ones would be useful for my project. Fortunately, I managed to filter out what I want.

Read more

How to Write a Simple Java Program to Check PageRank

In this article, I am not going to go in-depth about Java and Swing. The content I will share in this article is about how to combine slices of knowledge to make a simple java tool for checking PageRank. In my previous article, I talked about how to extract domain names from the urls that downloaded from Google Webmaster. Today, I will not only introduce a way to check the PR but also how to load an Excel file in Java to automatically test the batch of page PRs.

Read more

Dynamsoft’s First Open Source Software– MergeHero

A few days ago, Dynamsoft released its first open source software –Mergehero on SourceForge. It is a comparison tool for differing and merging files. The software complies with the GPL license that gives developers rights to access, modify, and redistribute source code.

What is the value of open source to users?

I think the general answer of using open-source software is that it is “free” for end-users. Who doesn’t like a free meal? Especially when the free meal is good. But in addition to being “free” for developers, it is even more. Developers are willing to learn and benefit from open source software. What is great is that they do not only absorb knowledge from someone else’s code, but that they can also make their own variant of the code.

Why does Dynamsoft provide open source?

For many years, Dynamsoft has been dedicated to being the dynamic center for software developers. Today, we are still making efforts to provide the best tools and services for the benefit of developers. I believe that the open source plan will be a win-win for both Dynamsoft and our users. Consider one of the well-known role models for open source plans, Google’s Android: Being open source allows it to rapidly spread and it has even caught up with iOS. Today, tons of people have become Android fans. They enjoy the open platform, and can make custom systems and custom UIs as they wish. We would like to see our customers use our software with the same passion. It provides positive energy.

What is MergeHero?

MergeHero is a simple diff tool written in Java. It is the key component of SourceAnywhere – a version control solution and VSS replacement – which is the star product of Dynamsoft.

Its features include:

  • Diff folders
  • Diff files (text files only)
  •  Merge files (text files only)
  • Cross-platform, including Mac OS, Windows, Linux

Screenshots of MergeHero functionalities:

diff folders

diff files

merge files

How to run MergeHero:

run mergehero

Some of Dynamsoft’s engineers are still contributing some code to the project in their spare time. We want to see more developers engage in this project, and have fun with the diff tool.

What is the Dynamsoft’s future plan about open source?

We have seen the trends that indicate that the amount of online education sites is skyrocketing, such as Coursera, Codecademy, Udacity, Code School, etc. The many free programming courses provided by these sites have brought power to the IT industry. In the meantime famous people, like Bill Gates and Mark Zuckberg, are also advocating coding education for young people. Inspired by these positive energies, Dynamsoft plans to provide more open source projects in the future. Not only on SourceForge, but also Github, Codeplex, Google Code etc. We want to see more and more users benefit from our software and share their knowledge with us.