Example usage for io.vertx.core.http HttpClient webSocket

List of usage examples for io.vertx.core.http HttpClient webSocket

Introduction

In this page you can find the example usage for io.vertx.core.http HttpClient webSocket.

Prototype

void webSocket(int port, String host, String requestURI, Handler<AsyncResult<WebSocket>> handler);

Source Link

Document

Connect a WebSocket to the specified port, host and relative request URI

Usage

From source file:fr.thibaultleouay.chat.client.parts.SamplePart.java

License:Open Source License

@PostConstruct
public void createComposite(Composite parent) {

    GridLayoutFactory.fillDefaults().applyTo(parent);

    textViewer = new StyledText(parent, SWT.V_SCROLL | SWT.WRAP);
    textViewer.setText("Start Chatting :");

    textViewer.setEditable(false);//from w  w w  . j ava2  s  .com
    textViewer.setEnabled(true);
    GridDataFactory.fillDefaults().grab(true, true).applyTo(textViewer);

    textInput = new Text(parent, SWT.BORDER);
    textInput.setMessage("Start entering text");
    textInput.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    buttonSend = new Button(parent, SWT.BORDER);
    buttonSend.setText("Send");
    GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonSend);
    buttonSend.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            // When we click our button we send our text input to the websocket
            websocket.writeFinalTextFrame(textInput.getText());
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {

        }
    });

    final Display display = Display.getCurrent();
    // We create our http client 
    HttpClient client = Vertx.vertx().createHttpClient();

    // We create our websocket on ws://localhost:8080 
    client.websocket(8080, "localhost", "", websocket -> {
        websocket.handler(data -> {
            //When we receive data from our websocket we update our widget though we should do it on the SWT thread 
            display.asyncExec(new Runnable() {
                @Override
                public void run() {
                    textViewer.setText(textViewer.getText() + "\n" + data.toString("UTF-8"));
                }
            });

        });

        this.websocket = websocket;
    });
}