Forum Stats

  • 3,827,674 Users
  • 2,260,803 Discussions
  • 7,897,332 Comments

Discussions

Web socket implementation

Nermin Ziric
Nermin Ziric Member Posts: 16 Red Ribbon
edited Feb 29, 2016 3:36AM in Java Applet Development

Hi guys,

is it possible to use websockets in java applet? if yes: any example?

Nermin Ziric

Answers

  • RuGI:.
    RuGI:. Member Posts: 67 Bronze Badge
    edited Feb 27, 2016 8:28PM

    Technically yes

    The only issue I see is that the applet must include the jars required to establish communication (which can cause the applet take a long time to load, although you can use the cache tags).

    Tyrus Apache(https://tyrus.java.net/) is the reference implementation for websocket in java  and requires Java 7 at least.

    See these examples:

    package websocket.client;

    import java.net.URI;

    import javax.websocket.*;

    @ClientEndpoint

    public class WSClient  {

        private static Object waitLock = new Object();

    @OnMessage

        public void onMessage(String message) {

    //the new USD rate arrives from the websocket server side.

           System.out.println("Received msg: "+message);      

        }

    private static void  wait4TerminateSignal()

    {

      synchronized(waitLock)

      {try {

        waitLock.wait();

       } catch (InterruptedException e) {  

       }}}

    public static void main(String[] args) {

    WebSocketContainer container=null;//

         Session session=null;

      try{

       //Tyrus is plugged via ServiceLoader API. See notes above

       container = ContainerProvider.getWebSocketContainer();

    //WS1 is the context-root of my web.app

    //ratesrv is the  path given in the ServerEndPoint annotation on server implementation

    session=container.connectToServer(WSClient.class, URI.create("ws://localhost:8080/WS1/ratesrv"));

       wait4TerminateSignal();

      } catch (Exception e) {

       e.printStackTrace();

      }

      finally{

       if(session!=null){

        try {

    session.close();

        } catch (Exception e) {   

         e.printStackTrace();

        }

       }       

      }

    }

    }

    Nermin ZiricNermin Ziric
  • Nermin Ziric
    Nermin Ziric Member Posts: 16 Red Ribbon
    edited Feb 29, 2016 3:36AM

    Thanks

    I will test it

    Nermin Ziric
This discussion has been closed.