Search in sources :

Example 1 with ServerHandshake

use of org.java_websocket.handshake.ServerHandshake in project quorrabot by GloriousEggroll.

the class Draft method createHandshake.

public List<ByteBuffer> createHandshake(Handshakedata handshakedata, Role ownrole, boolean withcontent) {
    StringBuilder bui = new StringBuilder(100);
    if (handshakedata instanceof ClientHandshake) {
        bui.append("GET ");
        bui.append(((ClientHandshake) handshakedata).getResourceDescriptor());
        bui.append(" HTTP/1.1");
    } else if (handshakedata instanceof ServerHandshake) {
        bui.append("HTTP/1.1 101 " + ((ServerHandshake) handshakedata).getHttpStatusMessage());
    } else {
        throw new RuntimeException("unknow role");
    }
    bui.append("\r\n");
    Iterator<String> it = handshakedata.iterateHttpFields();
    while (it.hasNext()) {
        String fieldname = it.next();
        String fieldvalue = handshakedata.getFieldValue(fieldname);
        bui.append(fieldname);
        bui.append(": ");
        bui.append(fieldvalue);
        bui.append("\r\n");
    }
    bui.append("\r\n");
    byte[] httpheader = Charsetfunctions.asciiBytes(bui.toString());
    byte[] content = withcontent ? handshakedata.getContent() : null;
    ByteBuffer bytebuffer = ByteBuffer.allocate((content == null ? 0 : content.length) + httpheader.length);
    bytebuffer.put(httpheader);
    if (content != null) {
        bytebuffer.put(content);
    }
    bytebuffer.flip();
    return Collections.singletonList(bytebuffer);
}
Also used : ServerHandshake(org.java_websocket.handshake.ServerHandshake) ClientHandshake(org.java_websocket.handshake.ClientHandshake) ByteBuffer(java.nio.ByteBuffer)

Example 2 with ServerHandshake

use of org.java_websocket.handshake.ServerHandshake in project intellij-community by JetBrains.

the class IpnbConnection method initializeClients.

protected void initializeClients() throws URISyntaxException {
    final Draft draft = new Draft17WithOrigin();
    myShellClient = new WebSocketClient(getShellURI(), draft, myHeaders, 0) {

        @Override
        public void onOpen(@NotNull ServerHandshake handshakeData) {
            final Message message = createMessage("connect_request", UUID.randomUUID().toString(), null, null);
            send(new Gson().toJson(message));
            myIsShellOpen = true;
            notifyOpen();
        }

        @Override
        public void onMessage(@NotNull String message) {
        }

        @Override
        public void onClose(int code, @NotNull String reason, boolean remote) {
        }

        @Override
        public void onError(@NotNull Exception e) {
        }
    };
    myShellThread = new Thread(myShellClient, "IPNB shell client");
    myShellThread.start();
    myIOPubClient = new IpnbWebSocketClient(getIOPubURI(), draft);
    myIOPubThread = new Thread(myIOPubClient, "IPNB pub client");
    myIOPubThread.start();
}
Also used : ServerHandshake(org.java_websocket.handshake.ServerHandshake) WebSocketClient(org.java_websocket.client.WebSocketClient) Draft(org.java_websocket.drafts.Draft)

Example 3 with ServerHandshake

use of org.java_websocket.handshake.ServerHandshake in project ChatExchange by HueToYou.

the class WebSocketBackend method createWebSocket.

/**
     * Creates the WebSocket using the provided URI
     * @param uri WebSocket URI
     */
private void createWebSocket(URI uri) {
    Map<String, String> headers = new HashMap<>();
    headers.put("Cookie", mRequestFactory.cookies());
    headers.put("Origin", "https://chat.stackexchange.com");
    mWebSocketClient = new WebSocketClient(uri, new Draft_17(), headers, 0) {

        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i(TAG, "WebSocket connection opened");
        }

        @Override
        public void onMessage(String s) {
            for (Event event : mGson.fromJson(s, WsMessage.class).events) {
                mBroadcaster.broadcastEvent(event);
            }
        }

        @Override
        public void onClose(int i, String s, boolean b) {
        // TODO
        }

        @Override
        public void onError(Exception e) {
            Log.e(TAG, e.getMessage());
        // TODO
        }
    };
}
Also used : ServerHandshake(org.java_websocket.handshake.ServerHandshake) HashMap(java.util.HashMap) Draft_17(org.java_websocket.drafts.Draft_17) WebSocketClient(org.java_websocket.client.WebSocketClient) JsonParseException(com.google.gson.JsonParseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) URISyntaxException(java.net.URISyntaxException)

Example 4 with ServerHandshake

use of org.java_websocket.handshake.ServerHandshake in project quorrabot by GloriousEggroll.

the class WebSocketImpl method decodeHandshake.

/**
     * Returns whether the handshake phase has is completed. In case of a broken
     * handshake this will be never the case.
	 *
     */
private boolean decodeHandshake(ByteBuffer socketBufferNew) {
    ByteBuffer socketBuffer;
    if (tmpHandshakeBytes.capacity() == 0) {
        socketBuffer = socketBufferNew;
    } else {
        if (tmpHandshakeBytes.remaining() < socketBufferNew.remaining()) {
            ByteBuffer buf = ByteBuffer.allocate(tmpHandshakeBytes.capacity() + socketBufferNew.remaining());
            tmpHandshakeBytes.flip();
            buf.put(tmpHandshakeBytes);
            tmpHandshakeBytes = buf;
        }
        tmpHandshakeBytes.put(socketBufferNew);
        tmpHandshakeBytes.flip();
        socketBuffer = tmpHandshakeBytes;
    }
    socketBuffer.mark();
    try {
        if (draft == null) {
            HandshakeState isflashedgecase = isFlashEdgeCase(socketBuffer);
            if (isflashedgecase == HandshakeState.MATCHED) {
                try {
                    write(ByteBuffer.wrap(Charsetfunctions.utf8Bytes(wsl.getFlashPolicy(this))));
                    close(CloseFrame.FLASHPOLICY, "");
                } catch (InvalidDataException e) {
                    close(CloseFrame.ABNORMAL_CLOSE, "remote peer closed connection before flashpolicy could be transmitted", true);
                }
                return false;
            }
        }
        HandshakeState handshakestate = null;
        try {
            if (role == Role.SERVER) {
                if (draft == null) {
                    for (Draft d : knownDrafts) {
                        d = d.copyInstance();
                        try {
                            d.setParseMode(role);
                            socketBuffer.reset();
                            Handshakedata tmphandshake = d.translateHandshake(socketBuffer);
                            if (tmphandshake instanceof ClientHandshake == false) {
                                flushAndClose(CloseFrame.PROTOCOL_ERROR, "wrong http function", false);
                                return false;
                            }
                            ClientHandshake handshake = (ClientHandshake) tmphandshake;
                            handshakestate = d.acceptHandshakeAsServer(handshake);
                            if (handshakestate == HandshakeState.MATCHED) {
                                resourceDescriptor = handshake.getResourceDescriptor();
                                ServerHandshakeBuilder response;
                                try {
                                    response = wsl.onWebsocketHandshakeReceivedAsServer(this, d, handshake);
                                } catch (InvalidDataException e) {
                                    flushAndClose(e.getCloseCode(), e.getMessage(), false);
                                    return false;
                                } catch (RuntimeException e) {
                                    wsl.onWebsocketError(this, e);
                                    flushAndClose(CloseFrame.NEVER_CONNECTED, e.getMessage(), false);
                                    return false;
                                }
                                write(d.createHandshake(d.postProcessHandshakeResponseAsServer(handshake, response), role));
                                draft = d;
                                open(handshake);
                                return true;
                            }
                        } catch (InvalidHandshakeException e) {
                        // go on with an other draft
                        }
                    }
                    if (draft == null) {
                        close(CloseFrame.PROTOCOL_ERROR, "no draft matches");
                    }
                    return false;
                } else {
                    // special case for multiple step handshakes
                    Handshakedata tmphandshake = draft.translateHandshake(socketBuffer);
                    if (tmphandshake instanceof ClientHandshake == false) {
                        flushAndClose(CloseFrame.PROTOCOL_ERROR, "wrong http function", false);
                        return false;
                    }
                    ClientHandshake handshake = (ClientHandshake) tmphandshake;
                    handshakestate = draft.acceptHandshakeAsServer(handshake);
                    if (handshakestate == HandshakeState.MATCHED) {
                        open(handshake);
                        return true;
                    } else {
                        close(CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match");
                    }
                    return false;
                }
            } else if (role == Role.CLIENT) {
                draft.setParseMode(role);
                Handshakedata tmphandshake = draft.translateHandshake(socketBuffer);
                if (tmphandshake instanceof ServerHandshake == false) {
                    flushAndClose(CloseFrame.PROTOCOL_ERROR, "wrong http function", false);
                    return false;
                }
                ServerHandshake handshake = (ServerHandshake) tmphandshake;
                handshakestate = draft.acceptHandshakeAsClient(handshakerequest, handshake);
                if (handshakestate == HandshakeState.MATCHED) {
                    try {
                        wsl.onWebsocketHandshakeReceivedAsClient(this, handshakerequest, handshake);
                    } catch (InvalidDataException e) {
                        flushAndClose(e.getCloseCode(), e.getMessage(), false);
                        return false;
                    } catch (RuntimeException e) {
                        wsl.onWebsocketError(this, e);
                        flushAndClose(CloseFrame.NEVER_CONNECTED, e.getMessage(), false);
                        return false;
                    }
                    open(handshake);
                    return true;
                } else {
                    close(CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake");
                }
            }
        } catch (InvalidHandshakeException e) {
            close(e);
        }
    } catch (IncompleteHandshakeException e) {
        if (tmpHandshakeBytes.capacity() == 0) {
            socketBuffer.reset();
            int newsize = e.getPreferedSize();
            if (newsize == 0) {
                newsize = socketBuffer.capacity() + 16;
            } else {
                assert (e.getPreferedSize() >= socketBuffer.remaining());
            }
            tmpHandshakeBytes = ByteBuffer.allocate(newsize);
            tmpHandshakeBytes.put(socketBufferNew);
        // tmpHandshakeBytes.flip();
        } else {
            tmpHandshakeBytes.position(tmpHandshakeBytes.limit());
            tmpHandshakeBytes.limit(tmpHandshakeBytes.capacity());
        }
    }
    return false;
}
Also used : HandshakeState(org.java_websocket.drafts.Draft.HandshakeState) Draft(org.java_websocket.drafts.Draft) ServerHandshake(org.java_websocket.handshake.ServerHandshake) Handshakedata(org.java_websocket.handshake.Handshakedata) IncompleteHandshakeException(org.java_websocket.exceptions.IncompleteHandshakeException) InvalidDataException(org.java_websocket.exceptions.InvalidDataException) ServerHandshakeBuilder(org.java_websocket.handshake.ServerHandshakeBuilder) InvalidHandshakeException(org.java_websocket.exceptions.InvalidHandshakeException) ClientHandshake(org.java_websocket.handshake.ClientHandshake) ByteBuffer(java.nio.ByteBuffer)

Aggregations

ServerHandshake (org.java_websocket.handshake.ServerHandshake)4 ByteBuffer (java.nio.ByteBuffer)2 WebSocketClient (org.java_websocket.client.WebSocketClient)2 Draft (org.java_websocket.drafts.Draft)2 ClientHandshake (org.java_websocket.handshake.ClientHandshake)2 JsonParseException (com.google.gson.JsonParseException)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 URISyntaxException (java.net.URISyntaxException)1 HashMap (java.util.HashMap)1 HandshakeState (org.java_websocket.drafts.Draft.HandshakeState)1 Draft_17 (org.java_websocket.drafts.Draft_17)1 IncompleteHandshakeException (org.java_websocket.exceptions.IncompleteHandshakeException)1 InvalidDataException (org.java_websocket.exceptions.InvalidDataException)1 InvalidHandshakeException (org.java_websocket.exceptions.InvalidHandshakeException)1 Handshakedata (org.java_websocket.handshake.Handshakedata)1 ServerHandshakeBuilder (org.java_websocket.handshake.ServerHandshakeBuilder)1