Skip navigation

Yesterday I’ve discovered GWTEventService. Today i started to play around with it, after some research in the example-svn and reading the docs, I was able to write my own “Hello World”.

This Hello World is a small chatting application. You are only able to send messages but not set a nickname or something similar.

Here you can see what it will look like:gwteventservice-helloworld1

In this short overview I’ll just show you the parts that are associated with the GWTEventSerice. The whole regular GWT UI/RPC stuff is left out. If you want to see the complete example, you can download it here.

First of all you need an Event:

public class MyEvent implements Event {
	public String message;

	public MyEvent(){}

	public MyEvent(String message) {
		this.setMessage(message);
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}

This Event gets fired when the server gets a new message from a client.

The next thing you need is a EventListener that gets notified when an Event occures:

public class MyListener implements RemoteEventListener {

	/**
	 * This function gets called by EventService
	 */
	public void apply(Event anEvent) {
		/**
		 * Check if the incoming Event is from the type MyEvent and if so, call the corresponding function
		 */
		if(anEvent instanceof MyEvent)
			onMyEvent((MyEvent)anEvent);
	}

	/**
	 * This function gets called when the incomming Event is from the Type MyEvent
	 *
	 * @param event
	 */
	public void onMyEvent(MyEvent event){}

}

The Listener receives the Events from the server an processes them.

Now on the client-side you need to register your Listener to the server:


	/**
	 * The domain to which we want to register our listener to
	 */
	private static final Domain DOMAIN = DomainFactory.getDomain("my_domain");

	public void onModuleLoad() {

		/**
		 * Create an EventService
		 */
		RemoteEventServiceFactory theEventServiceFactory = RemoteEventServiceFactory.getInstance();
		RemoteEventService theEventService = theEventServiceFactory.getRemoteEventService();

		/**
		 * Register our listener to the domain
		 */
		theEventService.addListener(DOMAIN, new MyListener(){
			public void onMyEvent(MyEvent event){
				/**
				 * Get the message from the event and append it to the allready received messages
				 */
				getIncommingMessages().setText( getIncommingMessages().getText() + event.getMessage() + "n" );
			}
		});

                [.....]
	}

On the client-side we just register our Listener, and tell him what to do when an Event occurs.

The last thing that we need is the Server:

public class HelloWorldServiceImpl extends RemoteEventServiceServlet implements HelloWorldService {

	/**
	 * The Domain that this Service sends Events to.
	 */
	private static final Domain DOMAIN = DomainFactory.getDomain("my_domain");

	/**
	 * A normal function that gets called when a client sends a message to the server.
	 */
	public void sendMessage(String message) {
		/**
		 * We dont save the incomming messages on the server. We just send an MyEvent to all
		 * registered Listeners on the Domain.
		 */
		this.addEvent(DOMAIN, new MyEvent(message));
	}

}

Instead of the default RemoteServiceServlet we extend this one with RemoteEventServiceServlet from the GWTEventService lib. This gives you the ability to send Events to the clients.

23 Comments

  1. I get the following error when I run this. Everything else seems to be working fine, but for some reason, the getDomain isn’t working. At least I think that’s where the problem is. Please respond if you can!

    [ERROR] Client-Error: Error on register client for domain!
    com.google.gwt.user.client.rpc.StatusCodeException:

    Error 404 NOT_FOUND

    HTTP ERROR: 404

    NOT_FOUND

    RequestURI=/gwteventservicehelloworld/gwteventservicePowered by Jetty://

    at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:192)
    at com.google.gwt.http.client.Request.fireOnResponseReceivedImpl(Request.java:264)
    at com.google.gwt.http.client.Request.fireOnResponseReceivedAndCatch(Request.java:236)
    at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:227)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
    at com.google.gwt.dev.shell.mac.MethodDispatch.invoke(MethodDispatch.java:71)
    at org.eclipse.swt.internal.carbon.OS.ReceiveNextEvent(Native Method)
    at org.eclipse.swt.widgets.Display.sleep(Display.java:3801)
    at com.google.gwt.dev.SwtHostedModeBase.sleep(SwtHostedModeBase.java:270)
    at com.google.gwt.dev.SwtHostedModeBase.processEvents(SwtHostedModeBase.java:265)
    at com.google.gwt.dev.HostedModeBase.pumpEventLoop(HostedModeBase.java:557)
    at com.google.gwt.dev.HostedModeBase.run(HostedModeBase.java:405)
    at com.google.gwt.dev.HostedMode.main(HostedMode.java:232)

  2. got it. just had to change some xml files.

    • I’m facing the same problem.
      Goathanger, what XML files did you have to update?

      Stelios

  3. me too. I have the same problem. I need this chatting application.

  4. try adding this line to the gwt.xml file:

    and adding this to war/WEB-INF/web.xml:

    GWTEventService
    de.novanic.eventservice.service.EventServiceImpl

    GWTEventService
    /projectName/gwteventservice

  5. I added in gwt.xml:



    <!– –>
    <!– –>

    and in the web.xml:

    EventService

    de.novanic.eventservice.service.EventServiceImpl

    EventService
    /gwteventservicetest/gwteventservice

    HelloWorldServlet
    com.demo.server.HelloWorldServiceImpl

    HelloWorldServlet
    /gwteventservicetest/HelloWorldService

    GWTEventServiceTest.html

    But I have the same erreur:

    ATTENTION: failed HelloWorldServlet
    java.lang.NoClassDefFoundError: de/novanic/eventservice/service/RemoteEventServiceServlet
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:142)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at org.mortbay.util.Loader.loadClass(Loader.java:91)
    at org.mortbay.util.Loader.loadClass(Loader.java:71)
    at org.mortbay.jetty.servlet.Holder.doStart(Holder.java:73)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:233)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:612)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:139)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1218)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:500)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117)
    at org.mortbay.jetty.Server.doStart(Server.java:217)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
    at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:152)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:116)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:218)
    at com.google.appengine.tools.development.gwt.AppEngineLauncher.start(AppEngineLauncher.java:86)
    at com.google.gwt.dev.HostedMode.doStartUpServer(HostedMode.java:365)
    at com.google.gwt.dev.HostedModeBase.startUp(HostedModeBase.java:589)
    at com.google.gwt.dev.HostedModeBase.run(HostedModeBase.java:397)
    at com.google.gwt.dev.HostedMode.main(HostedMode.java:232)
    Caused by: java.lang.ClassNotFoundException: de.novanic.eventservice.service.RemoteEventServiceServlet
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:142)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    … 35 more

    • Have you added the gwteventservice jars to you Classpath?

  6. Yes, I added this library on my project.

  7. hi
    i’m about to learn how to use GWT & EventService , each time i try to understand how its work i face a new problem, i asked the community but still there is no answer,so i started to search and found your blog and your source code that is very nice and clean.
    but i still couldn’t compile and run it.
    i tested with GWT 1.5 , 1.7 & 2.0
    none of them works.
    shouldn’t i create a GWT Project and add the eventService to the classpath ? should i make a Java project and add the GWT and eventService to its classPath?
    can you please help me on compiling and running your project
    thanks.

  8. Due to the problems many of you have with this example i have imported the zip-file as a new project in a clean eclipse installation.

    Besides some errors about the unbound GWT_HOME var everything worked fine. Which errors does eclipse show in your problems-view?

    daniel

  9. thanks for you consideration
    here are the steps that i do :
    1. unzip the folder
    2. import it to the eclipse
    3. right click on the project select run as > Run On server > Tomcat v6 server at localhost > finish
    and here is the image of result :

    should i change the url ?
    can you please help me what should i do
    thanks

    Bamdad Dashtban

  10. It looks as if you havent enabled GWT for the project.

    Rightclick on the project -> google -> web toolkit settings -> use gwt web toolkit.

    Then you should be able to select “run as web application”

  11. thanks it works.

  12. i was checking your code today ,and i found it works with gwt 1.5 but fails with gwt 1.7 & gwt 2, also the code that returns void for the interface had errors in IDE (HelloWorldService & HelloWorldAsync ) .
    have you checked your code with gwt 2 ?

  13. i’ve ported your example into GWT 2.
    thanks for you greate tutorial.
    here is my code :
    http://www.irangwt.co.cc/gwt/GwtChatBoard2.rar

  14. Hi, guys

    The tut is really cool but I cannot really make it work. I have GWT 2.3 and each time I start it I get error 500 :S
    I am trying, as an example, make client “Test” (which in one project) sends and receives message just to see how the service works;
    The client invokes sendMessage(String message) method to get message back to my client but that causes an error ;
    I suppose it is all because I use code which returns String but the original one is a void one; But the thing is GWT 2.3 throws that there is no way to return Object type so I cannot use void :X

    AServiceAsync s=(AServiceAsync)GWT.create(AService.class);
    AsyncCallback callback=new AsyncCallback()
    {

    @Override
    public void onFailure(Throwable caught) {
    // TODO Auto-generated method stub

    }

    @Override
    public void onSuccess(String result) {

    }

    };

    s.sendMessage(message, callback);

    Has somebody faced the same thing? Can you advice something? How to make it work with GWT 2.3?

  15. I should leave a comment to Thank You.
    You really save my ass, I try to understand the official example but they all complicated.
    However your example is so clear and easy to understand!
    Again, thanks for saving me from my university project.

  16. Reblogged this on Share Coding and commented:
    The most clear and easy understanding Comet(Server-push) Tutorial

  17. Superb, what a blog it is! This website
    gives valuable information to us, keep it up.
    Вклады втб 24 для пенсионеров в
    2013 году Оформить кредитную карту онлайн русский стандарт голд Как получить ипотеку
    в лондоне Кредит на карту кукуруза
    онлайн [http://kredit-na-kartu-kukuruza-onlayn.investmentfinance.ru] Кредитная карта кукуруза Сбербанк кредитный калькулятор ипотека (sberbank-kreditnyy-kalkulyator-ipoteka.
    investmentfinance.ru) Жк лебединое озеро ипотека Россельхозбанк кредиты
    онлайн заявка Рейтинг банков по вкладам
    2011 Заявка на кредит онлайн русский стандарт
    карта Восточный экспресс банк эмблема
    Потребительский кредит без прописки
    Сбербанк потребительский
    кредит договор Денежные кредиты в русском
    стандарте Деньги в кредит за час Оформить
    кредитную карту за один день Гераклит вклад в
    психологию (geraklit-vklad-v-psihologiyu.
    investmentfinance.ru) Кредит без справок и поручителей тверь Оф сайт хоум
    кредит Вклад в экономику Кредитные карты
    сбербанка россии моментум Хоум кредит банк тюмень [houm-kredit-bank-tyumen.investmentfinance.ru] Банковские вклады для
    пенсионеров Альфа банк воронеж кредитная карта *alfa-bank-voronezh-kreditnaya-karta.
    investmentfinance.ru* Кредит ипотека под материнский капитал (kredit-ipoteka-pod-materinskiy-kapita.

    investmentfinance.ru) Продажа кредитов ougos Банк
    новосибирск потребительский кредит
    йошкар ола Как активировать кредитную карту ренессанс Что необходимо для получения ипотечного кредита [http://chto-neobhodimo-dlya-polucheniya-ipotechnogo-kredita.investmentfinance.ru] Вклады в
    банках беларуси в российских рублях Вклады
    в банках белоруссии Машина в кредит г
    сумы Банк кольцо урала потребительские кредиты ebesucher Просрочка по кредитам в россии (prosrochka-po-kreditam-v-rossii.
    investmentfinance.ru) Роль кредита в развитии экономики его границы
    (rol-kredita-v-razvitii-ekonomiki-ego-granicy.investmentfinance.

    ru) Государственный кредит государство как заемщик
    Сущность ипотечного кредитования в россии Народный кредит журнал Заявка на кредитную карту сбербанка 2013 Закон
    о кредитных авто (zakon-o-kreditnyh-avto.
    investmentfinance.ru) Если задолженность по кредиту Специалист по автокредитованию без опыта Россельхозбанк кредит
    с 18 лет Тинькофф кредитная карта
    где снять наличные Потребительский кредит по двум документам самара Как заполнить анкету на ипотеку сбербанк Центр
    автокредитования втб 24 спб Вклад имущества в уставный
    капитал Мтс кредит адреса – http://mts-kredit-adresa.

    investmentfinance.ru – Iphone в кредит минск
    Кредит в сбербанке требования (http:
    //kredit-v-sberbanke-trebovaniya.investmentfinance.ru) Kredit 1 tag Рефинансирование потребительского кредита втб 24 ярославль Взять кредит в
    сбербанке россии пенсионеру Сумма страхования вкладов физических лиц до
    1 млн Сбербанк потребительский кредит под поручительство физических лиц Ставки по вкладам
    скб банк Социальная ипотека хабаровск куда обращаться
    Тинькофф кредитная карта узнать лимит

  18. I am really enjoying the theme/design of your blog.
    Do you ever run into any web browser compatibility issues?
    A handful of my blog audience have complained about my site not
    operating correctly in Explorer but looks great in Safari.
    Do you have any ideas to help fix this problem?

  19. Aw, this was a very nice post. In thought I want to put in writing like this moreover taking time and actual effort to make an excellent article but what can I say I procrastinate alot and not at all seem to get something done. ceffgdabdkdd

  20. займ онлайн на карту на год: https://citycredits.com.ua/

  21. find out here https://cazino-v.online


One Trackback/Pingback

  1. […] = "#FFFFFF"; ch_color_text = "#000000"; ch_color_bg = "#FFFFFF"; I am trying to make this example; I just faced a strange error which happens when sendMessage(String msg) method is […]

Leave a reply to luck0r Cancel reply