Posts Tagged ‘WebSocket’
[DevoxxBE2013] Part 1: Java EE 7: What’s New in the Java EE Platform
Antonio Goncalves and Arun Gupta, luminaries in Java EE advocacy, deliver a comprehensive exploration of Java EE 7’s advancements, blending simplification with expanded capabilities. Antonio, a senior architect and author of Beginning Java EE 6 Platform with GlassFish 3, collaborates with Arun, Red Hat’s Director of Developer Advocacy and former Java EE pioneer at Sun Microsystems, to unveil WebSocket, JSON processing, and enhanced CDI and JTA features. Their session, rich with demos, highlights how these innovations bolster HTML5 support and streamline enterprise development.
Java EE 7, they assert, refines container services while embracing modern web paradigms. From WebSocket’s real-time communication to CDI’s unified bean management, they showcase practical integrations, ensuring developers can craft scalable, responsive applications.
WebSocket for Real-Time Communication
Antonio introduces WebSocket, a cornerstone for HTML5’s bidirectional connectivity. He demonstrates @ServerEndpoint-annotated classes, crafting a chat application where messages flow instantly, bypassing HTTP’s overhead.
Arun details encoders/decoders, transforming POJOs to wire-ready text or binary frames, streamlining data exchange for real-time apps like live dashboards.
JSON Processing and JAX-RS Enhancements
Arun explores JSON-P (JSR 353), parsing and generating JSON with a fluid API. He demos building JSON objects from POJOs, integrating with JAX-RS’s HTTP client for seamless RESTful interactions.
This synergy, Antonio notes, equips developers to handle data-driven web applications, aligning with HTML5’s data-centric demands.
CDI and Managed Bean Alignment
Antonio unveils CDI’s evolution, unifying managed beans with injectable interceptors. He showcases constructor injection and method-level validation, simplifying dependency management across EJBs and servlets.
Arun highlights JTA’s declarative transactions, enabling @Transactional annotations to streamline database operations, reducing boilerplate.
Simplified JMS and Batch Processing
Arun introduces JMS 2.0’s simplified APIs, demonstrating streamlined message publishing. The new Batch API (JSR 352), Antonio adds, orchestrates chunk-based processing for large datasets, with demos showcasing job definitions.
These enhancements, they conclude, enhance usability, pruning legacy APIs while empowering enterprise scalability.
Resource Definitions and Community Engagement
Antonio details expanded resource definitions, configuring data sources via annotations. Arun encourages JCP involvement, noting Java EE 8’s community-driven roadmap.
Their demos—leveraging GlassFish—illustrate practical adoption, inviting developers to shape future specifications.
Links:
[DevoxxFR2013] Soon, in a Galaxy Not So Far Away: Real-Time Web with Play 2, Akka, and Spaceships
Lecturer
Mathieu Ancelin is a software engineer at SERLI, specializing in Java EE technologies with a particular focus on component frameworks. He contributes to open-source projects such as GlassFish, JOnAS, and leads initiatives like CDI-OSGi and Play CDI. A member of the JSR 346 expert group for CDI 1.1, Ancelin regularly teaches at the University of La Rochelle and Poitiers, and speaks at conferences including JavaOne and Solutions Linux. He is active in the Poitou-Charentes JUG and can be followed on Twitter as @TrevorReznik.
Abstract
Mathieu Ancelin demystifies Play 2’s real-time capabilities, answering the perennial question: “WTF are Iteratees?” Through live demonstrations of two playful applications—a multiplayer spaceship battle and a real-time roulette game—he showcases how Play 2 leverages Iteratees, Akka actors, Server-Sent Events (SSE), WebSockets, HTML5 Canvas, and even webcam input to build responsive, interactive web experiences. The session explores how these APIs integrate seamlessly with Java and Scala, enabling developers to create low-latency, event-driven systems using their preferred language. Beyond the fun, Ancelin analyzes architectural patterns for scalability, backpressure handling, and state management in real-time web applications.
Demystifying Iteratees: Functional Streams for Non-Blocking I/O
Ancelin begins by addressing the confusion surrounding Iteratees, a functional reactive programming abstraction in Play 2. Unlike traditional imperative streams, Iteratees separate data production, processing, and consumption, enabling composable, backpressure-aware pipelines.
val enumeratee: Enumeratee[Array[Byte], String] = Enumeratee.map[Array[Byte]].apply[String] { bytes =>
new String(bytes, "UTF-8")
}
This allows safe handling of chunked HTTP input without blocking threads. When combined with Enumerators (producers) and Enumeratees (transformers), they form robust data flows:
val socket: WebSocket[JsValue, JsValue] = WebSocket.using[JsValue] { request =>
val in = Iteratee.foreach[JsValue](msg => actor ! msg).map(_ => actor ! PoisonPill)
val out = Enumerator.fromCallback1(_ => futurePromise.future)
(in, out)
}
Ancelin demonstrates how this pattern prevents memory leaks and thread exhaustion under load.
Akka Actors: Coordinating Game State and Player Actions
The spaceship game uses Akka actors to manage shared game state. A central GameActor maintains positions, velocities, and collisions:
class GameActor extends Actor {
var players = Map.empty[String, Player]
val ticker = context.system.scheduler.schedule(0.millis, 16.millis, self, Tick)
def receive = {
case Join(id, out) => players += (id -> Player(out))
case Input(id, thrust, rotate) => players(id).update(thrust, rotate)
case Tick => broadcastState()
}
}
Each client connects via WebSocket, sending input events and receiving rendered frames. The actor model ensures thread-safe updates and natural distribution.
Real-Time Rendering with Canvas and Webcam Integration
The game renders on HTML5 Canvas using client-side JavaScript. Server pushes state via SSE or WebSocket; client interpolates between ticks for smooth 60 FPS animation.
A bonus feature uses getUserMedia() to capture webcam input, mapping head tilt to ship rotation—an engaging demo of sensor fusion in the browser.
navigator.getUserMedia({ video: true }, stream => {
video.src = URL.createObjectURL(stream);
tracker.on('track', event => sendRotation(event.data.angle));
});
Play Roulette: SSE for Unidirectional Live Updates
The second demo, Play Roulette, uses Server-Sent Events to broadcast spin results to all connected clients:
def live = Action {
Ok.chunked(results via EventSource()).as("text/event-stream")
}
Clients subscribe with:
const es = new EventSource('/live');
es.onmessage = e => updateWheel(JSON.parse(e.data));
This pattern excels for broadcast scenarios—news feeds, dashboards, live sports.
Language Interoperability: Java and Scala Working Together
Ancelin emphasizes Play 2’s dual-language support. Java developers use the same APIs via wrappers:
public static WebSocket<JsonNode> socket() {
return WebSocket.withActor(GameActor::props);
}
This lowers the barrier for Java teams adopting reactive patterns.
Architecture Analysis: Scalability, Fault Tolerance, and Deployment
The system scales horizontally using Akka clustering. Game instances partition by room; a load balancer routes WebSocket upgrades. Failure recovery leverages supervisor strategies.
Deployment uses Play’s dist task to generate start scripts. For production, Ancelin recommends Typesafe ConductR or Docker with health checks.
Implications for Modern Web Applications
Play 2’s real-time stack enables:
– Low-latency UX without polling
– Efficient resource use via non-blocking I/O
– Graceful degradation under load
– Cross-language development in polyglot teams
From games to trading platforms, the patterns apply broadly.
Links:
[DevoxxBE2013] Java EE 7’s Java API for WebSocket
Arun Gupta, Director of Developer Advocacy at Red Hat, unveils the transformative capabilities of the Java API for WebSocket in Java EE 7. A veteran of Sun Microsystems and Oracle, Arun has championed Java technologies globally, authoring extensive blogs and a best-selling book. His session explores WebSocket’s role in enabling efficient, bidirectional communication, eliminating the need for long polling or AJAX. Through live demonstrations, he illustrates server-side endpoints and client-side integrations, showcasing how this API empowers developers to craft responsive web and rich client applications.
WebSocket, a cornerstone of HTML5, facilitates real-time data exchange over a single TCP connection. Arun highlights its scalability, with GlassFish handling thousands of connections, and introduces tools like Autobahn for compliance testing. This API positions Java developers to build dynamic, scalable systems that complement RESTful architectures.
WebSocket Fundamentals and API Design
Arun introduces WebSocket’s departure from HTTP’s request-response model, leveraging a single, persistent connection. Using annotations like @ServerEndpoint, he demonstrates creating a chat application where messages flow instantly. The client API, accessible from browsers or Java applications, enables seamless integration.
This simplicity, Arun notes, reduces latency, making WebSocket ideal for real-time applications like live updates or collaborative tools.
Server-Side Scalability and Performance
Scalability is a key strength, Arun explains, with WebSocket supporting millions of file descriptors on Linux. He recounts Oracle’s GlassFish tests, achieving robust performance with thousands of connections. The Autobahn test suite, he suggests, validates compliance and load capacity.
Forthcoming WildFly tests, Arun adds, will further benchmark performance, ensuring reliability in production environments.
Complementing REST with WebSocket
Arun clarifies that WebSocket complements JAX-RS, not replaces it. He illustrates a hybrid design: REST for stateless queries, WebSocket for real-time updates. A stock ticker demo shows prices pushed to clients, blending both paradigms.
This synergy, Arun argues, enhances application flexibility, with Java EE 8 discussions exploring further integrations.
Community Engagement and Future Directions
Arun encourages joining Java EE expert groups, noting their transparent processes. Recent community gatherings, he mentions, discussed enhancing WebSocket’s role. He advocates contributing to shape Java EE 8, ensuring it meets developer needs.
This collaborative approach, Arun emphasizes, drives innovation, aligning WebSocket with evolving web standards.