Vous êtes sur la page 1sur 14

6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

Creating Binary WebSocket Connections with Java EE 7 and JavaFX

Overview

Creating a Web Applic ation

In this section, you create a Java EE 7 web application in the NetBeans IDE.

1. Select File > New Project.

2. In the New Project dialog box, perform the following steps:

a. Select Java Web from Categories.


b. Select Web Application from Projects.
c. Click Next.

3. On the Name and Location page, enter BinaryWebSocketServeras the project name and click Next.

4. On the Server and Settings page, perform the following steps:

a. Select GlassFish Server 4.0 from the Server list.


b. Select Java EE 7 Web from the Java EE Version list.
c. Click Finish.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 1/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

The BinaryWebSocketServerproject is created in NetBeans.

Creating the Binary WebSoc ket Server Endpoint

In this section, you create the WebSocket server endpoint.

1. Right-click the BinaryWebSocketServerproject and select New > Other.

2. On the New File page, perform the following steps:

a. Select the Web category.


b. Select the WebSocket Endpoint file type.
c. Click Next.

3. On the Create WebSocket Endpoint page, perform the following steps:

a. Enter BinaryWebSocketServerfor the class name.


http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 2/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.
a. Enter BinaryWebSocketServerfor the class name.
b. Enter com.demo.websocketfor the project name.
c. Enter /imagesfor the WebSocket URI.
d. Click Finish.

4. Add a static Setof Sessionobjects just below the public class BinaryWebSocketServer {definition to store connected

private
static final Set<Session> sessions =
Collections.synchronizedSet(new HashSet<Session>());

5. Add the following imports after the package com.demo.websocketdeclaration:

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Session;

Alternatively, you can import the classes by selecting the Fix Imports option.

1. From the NetBeans menu, select Source > Fix Imports.

2. In the Fix All Imports dialog box, select the classes that you want to import and click OK.

6. Add the following two methods to add and remove sessions:


http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 3/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.
6. Add the following two methods to add and remove sessions:

@OnOpen
public void onOpen(Session session) {
sessions.add(session);
}

@OnClose
public void onClose(Session session) {
sessions.remove(session);
}

7. Add the following imports:

import javax.websocket.OnClose;
import javax.websocket.OnOpen;

8. Modify the onMessagemethod.

@OnMessage
public void onMessage(ByteBuffer byteBuffer) {
for (Session session : sessions) {
try {
session.getBasicRemote().sendBinary(byteBuffer);
} catch (IOException ex) {
Logger.getLogger(BinaryWebSocketServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

9. Add the following imports:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

Use the following completed BinaryWebSocketServercode sample for reference:

package com.demo.websocket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/images")
public class BinaryWebSocketServer {

private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

@OnOpen
public void onOpen(Session session) {
sessions.add(session);
}

@OnClose
public void onClose(Session session) {
sessions.remove(session);
}

@OnMessage
public void onMessage(ByteBuffer byteBuffer) {
for (Session session : sessions) {
try {
session.getBasicRemote().sendBinary(byteBuffer);
} catch (IOException ex) {
Logger.getLogger(BinaryWebSocketServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

Creating the JavaFX Projec t

In this section, you create the WebSocket client application.

1. Select File > New Project.

2. In the New Project dialog box, perform the following steps:

a. Select JavaFX from the Categories list.


b. Select JavaFX Application from the Projects list.
c. Click Next.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 4/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

3. On the Name and Location page, enter JavaFXBinaryWsClientfor the project name and click Finish.

To use WebSocket in Java SE/FX applications, you need additional JAR libraries. This example uses Project Tyrus, which is the ref
WebSockets. The required JAR files are provided as part of this tutorial.

4. Right-click JavaFXBinaryWsClientand select New > Other.

5. On the Choose File page, perform the following steps:

a. Select Other from the Categories list.


b. Select Folder from the File Types list.
c. Click Next.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 5/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

6. On the Name and Location page, enter libfor the folder name and click Finish.

7. Add the WebSocket implementation JARs to the project.

a. Download the WebSocket Client Jars from this zip file.


b. Extract the files to the libfolder of the JavaFXBinaryWsClientproject.

You can view the files in NetBeans on the Files tab.

8. Right-click the JavaFXBinaryWsClientproject and select Properties.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 6/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

9. Select the Libraries page and click Add JAR/Folder.

10. In the Add JAR/Folder dialog box, add the unzipped JAR files.

a. Browse to the lib folder in the JavaFXBinaryWsClientproject.


b. Select all of the JAR files.
c. Click Open.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 7/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

11. In the Project Properties dialog box, click OK.

If you see a reference warning about the dist.jarfile, ignore it. The file is built with the project

Creating the JavaFX Client

In this section, you build the JavaFX binary WebSocket client.

You will:

Connect to the WebSocket server.

Create a simple JavaFX layout.

Send and receive binary WebSocket messages.

1. Open the javafxbinarywsclient.JavaFxBinaryWsClientJava class.

2. Annotate the class with the @javax.websocket.ClientEndpointannotation.

View Code

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 8/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.
3. Add the following instance variables:

A private javax.websocket.Session sessionto communicate messages to the server

A private javafx.scene.image.ImageView imageViewto display images sent from the server


A private static final Logger LOGGER = Logger.getLogger(JavaFXBinaryWsClient.class.getName());

@ClientEndpoint
public class JavaFXBinaryWsClient extends Application {

private Session session;


private ImageView ImageView;
private static final Logger LOGGER = Logger.getLogger(JavaFXBinaryWsClient.class.getName());

Add the following imports:

import java.util.logging.Logger;
import javafx.scene.image.ImageView;
import javax.websocket.Session;

4. Add a method to connect to the WebSocket server.

private void connectToWebSocket() {


WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
URI uri = URI.create("ws://localhost:8080/BinaryWebSocketServer/images");
container.connectToServer(this, uri);
} catch (DeploymentException | IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
System.exit(-1);
}
}

This method configures the running application as a WebSocket client.

5. Add the following imports:

import java.io.IOException;
import java.net.URI;
import java.util.logging.Level;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.WebSocketContainer;

6. At the beginning of the startmethod, invoke the connectToWebSocketmethod.

@Override
public void start(final Stage primaryStage) {
connectToWebSocket();

7. Replace the contents of the startmethod after the connectToWebSocket()call to create the layout.

At a minimum, your layout needs the following:

A javafx.scene.control.Buttonto select an image to send


A javafx.scene.image.ImageViewto display images received

The following code uses an AnchorPaneto arrange the components:

@Override
public void start(final Stage primaryStage) {
connectToWebSocket();
Button btn = new Button();
btn.setText("Send Image!");
btn.setPrefSize(400, 27);

imageView = new ImageView();


imageView.setFitHeight(400);
imageView.setFitWidth(400);
imageView.setPreserveRatio(true);
imageView.setSmooth(true);

AnchorPane root = new AnchorPane();

AnchorPane.setTopAnchor(btn, 0.0);
AnchorPane.setLeftAnchor(btn, 0.0);
AnchorPane.setRightAnchor(btn, 0.0);
AnchorPane.setTopAnchor(imageView, 27.0);
AnchorPane.setBottomAnchor(imageView, 0.0);
AnchorPane.setLeftAnchor(imageView, 0.0);
AnchorPane.setRightAnchor(imageView, 0.0);

root.getChildren().add(btn);
root.getChildren().add(imageView);

Scene scene = new Scene(root, 400, 427);

primaryStage.setTitle("Image push!");
primaryStage.setScene(scene);
primaryStage.show();
}

8. Add the following import:

javafx.scene.layout.AnchorPane;

9. Create a method to select and send an image.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 9/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

private void selectAndSendImage(Stage stage) {


FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Image to Send");
File file = fileChooser.showOpenDialog(stage);
try (InputStream input = new FileInputStream(file);
OutputStream output = session.getBasicRemote().getSendStream()) {
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}

10. Add the following imports:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javafx.stage.FileChooser;

11. Create an event handler for the button and invoke the selectAndSendImagemethod. Make the stage method parameter in the start
handler.

btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
selectAndSendImage(primaryStage);
}
});

12. Add the following imports:

import javafx.event.ActionEvent;
import javafx.event.EventHandler;

13. Create the WebSocket methods to handle connections and messages.

A method annotated by javax.websocket.OnOpenthat sets the session variable


A method annotated by javax.websocket.OnClosethat attempts to reconnect if the connection is closed
A method annotated by javax.websocket.OnMessagethat handles the messages and creates an image to be displayed in t

@OnOpen
public void onOpen(Session session) {
this.session = session;
}

@OnMessage
public void onMessage(InputStream input) {
System.out.println("WebSocket message Received!");
Image image = new Image(input);
imageView.setImage(image);
}

@OnClose
public void onClose() {
connectToWebSocket();
}

14. Add the following imports:

import javafx.scene.image.Image;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;

Use the following completed JavaFXBinaryWsClientsource code for reference:

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 10/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

package javafxbinarywsclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class JavaFXBinaryWsClient extends Application {

private static final Logger LOGGER = Logger.getLogger(JavaFXBinaryWsClient.class.getName());


private ImageView imageView;
private Session session;

@OnOpen
public void onOpen(Session session) {
this.session = session;
}

@OnMessage
public void onMessage(InputStream input) {
System.out.println("WebSocket message Received!");
Image image = new Image(input);
imageView.setImage(image);
}

@OnClose
public void onClose() {
connectToWebSocket();
}

@Override
public void start(final Stage primaryStage) {
connectToWebSocket();

Button btn = new Button();


btn.setText("Send Image!");
btn.setPrefSize(400, 27);
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
selectAndSendImage(primaryStage);
}
});
imageView = new ImageView();
imageView.setFitHeight(400);
imageView.setFitWidth(400);
imageView.setPreserveRatio(true);
imageView.setSmooth(true);

AnchorPane root = new AnchorPane();

AnchorPane.setTopAnchor(btn, 0.0);
AnchorPane.setLeftAnchor(btn, 0.0);
AnchorPane.setRightAnchor(btn, 0.0);
AnchorPane.setTopAnchor(imageView, 27.0);
AnchorPane.setBottomAnchor(imageView, 0.0);
AnchorPane.setLeftAnchor(imageView, 0.0);
AnchorPane.setRightAnchor(imageView, 0.0);

root.getChildren().add(btn);
root.getChildren().add(imageView);

Scene scene = new Scene(root, 400, 427);

primaryStage.setTitle("Image push!");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}

private void selectAndSendImage(Stage stage) {


FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Image to Send");
File file = fileChooser.showOpenDialog(stage);
try (InputStream input = new FileInputStream(file);
OutputStream output = session.getBasicRemote().getSendStream()) {
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) > 0) {
output.write(buffer, 0, read);
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}

private void connectToWebSocket() {


WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
URI uri = URI.create("ws://localhost:8080/BinaryWebSocketServer/images");
container.connectToServer(this, uri);
} catch (DeploymentException | IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
System.exit(-1);
}
}
}

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 11/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.
}

Running and Testing the Applic ation

1. Run the BinaryWebSocketServerproject: Right-click the BinaryWebSocketServerproject and select Run.

The http://localhost:8080/BinaryWebSocketServer URL opens in a web browser after GlassFish server starts.

2. Run the JavaFXBinaryWsClientproject: Right-click the JavaFXBinaryWsClientproject and select Run.

A new window with the JavaFX application opens.

3. Repeat step 2 to run another instance of the JavaFXBinaryWsClient project. (Do not close the window.)

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 12/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.

Two windows are running.

4. In one of the windows, press the Send Image! button, browse for an image, and open it.

The image is displayed in both windows.

5. Open more instances of the JavaFX applications and send another image. All instances will receive and display the images.

Summary

In this tutorial, you learned to:


http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 13/14
6/29/2017 Using binary WebSockets with Java EE 7 and JavaFX clients.
In this tutorial, you learned to:

Create Binary WebSocket services with Java EE7


Create Binary WebSocket clients with Java FX

Next Steps

This is a simple tutorial for binary WebSockets. You can try to implement more complex scenarios, such as the following, and use

Save the image on the server to send it to newly connected users.


Send the latest three images to the clients.
Combine text messages with images to create an image-based chat client.
Stream videos as a sequence of images.

Resources

To learn more about WebSockets or Java EE7, see the following resources:

JSR 356: JavaTM API for WebSocket


WebSocket Java EE7 Tutorial
Java EE Technical Documentation
Java FX Documentation
Project Tyrus, WebSocket Reference Implementation.
Using WebSocket for Real-Time Communication in Java Platform, Enterprise Edition 7 OBE
Java EE 7: New Features

Credits

Lead Curriculum Developer: Eduardo Moranchel

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/BinaryWebSocket/binaryWebSocket.html 14/14

Vous aimerez peut-être aussi