Java Examples for org.java_websocket.client.WebSocketClient
The following java examples will help you to understand the usage of org.java_websocket.client.WebSocketClient. These source code samples are taken from different open source projects.
Example 1
Project: libGDX-Net-master File: WSClient.java View source code |
public void connectClient(String ip) {
if (!ip.isEmpty()) {
//Websocket implementation
//URI (url address of the server)
URI url = null;
try {
//We create the URI of the server. Use a port upper than 1024 on Android and Linux!
url = new URI("ws://" + ip + ":" + port);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//We select the standard implementation of WebSocket
Draft standard = new Draft_17();
wsc = new WebSocketClient(url, standard) {
@Override
public void onOpen(ServerHandshake handshake) {
connected = true;
requestID();
}
@Override
public void onMessage(String message) {
//SERVER CLOSES MY WS CONNECTION.
if (message.equals("MSG_CLOSE_WS")) {
this.close();
} else //SERVER SEND MY CLIENT ID.
if (message.startsWith("MSG_SEND_ID")) {
//splitter with the " " separator
String[] values = message.split("\\s+");
myID = Integer.valueOf(values[1]);
} else //High level Message, send to the ClientMSG class
{
c.onMessage(message);
}
}
@Override
public void onError(Exception ex) {
System.out.println("WSClient Error.");
}
@Override
public void onClose(int code, String reason, boolean remote) {
connected = false;
}
};
//And we create the connection between client and server
wsc.connect();
}
}
Example 2
Project: roborace-master File: SimpleClient.java View source code |
public void actionPerformed(ActionEvent e) {
if (e.getSource() == chatField) {
if (cc != null) {
cc.send(chatField.getText());
chatField.setText("");
chatField.requestFocus();
}
} else if (e.getSource() == connect) {
try {
// cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() );
cc = new WebSocketClient(new URI(uriField.getText()), (Draft) draft.getSelectedItem()) {
@Override
public void onMessage(String message) {
ta.append("got: " + message + "\n");
ta.setCaretPosition(ta.getDocument().getLength());
}
@Override
public void onOpen(ServerHandshake handshake) {
ta.append("You are connected to ChatServer: " + getURI() + "\n");
ta.setCaretPosition(ta.getDocument().getLength());
}
@Override
public void onClose(int code, String reason, boolean remote) {
ta.append("You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n");
ta.setCaretPosition(ta.getDocument().getLength());
connect.setEnabled(true);
uriField.setEditable(true);
draft.setEditable(true);
close.setEnabled(false);
}
@Override
public void onError(Exception ex) {
ta.append("Exception occured ...\n" + ex + "\n");
ta.setCaretPosition(ta.getDocument().getLength());
ex.printStackTrace();
connect.setEnabled(true);
uriField.setEditable(true);
draft.setEditable(true);
close.setEnabled(false);
}
};
close.setEnabled(true);
connect.setEnabled(false);
uriField.setEditable(false);
draft.setEditable(false);
cc.connect();
} catch (URISyntaxException ex) {
ta.append(uriField.getText() + " is not a valid WebSocket URI\n");
}
} else if (e.getSource() == close) {
cc.close();
}
}
Example 3
Project: Connect-SDK-Android-Core-master File: WebOSTVMouseSocketConnection.java View source code |
public void connectPointer(URI uri) {
if (ws != null) {
ws.close();
ws = null;
}
ws = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake arg0) {
Log.d("PtrAndKeyboardFragment", "connected to " + uri.toString());
if (listener != null) {
listener.onConnected();
}
}
@Override
public void onMessage(String arg0) {
}
@Override
public void onError(Exception arg0) {
}
@Override
public void onClose(int arg0, String arg1, boolean arg2) {
}
};
ws.connect();
}
Example 4
Project: java-client-master File: WebsocketTransport.java View source code |
@Override
public SignalRFuture<Void> start(ConnectionBase connection, ConnectionType connectionType, final DataResultCallback callback) {
final String connectionString = connectionType == ConnectionType.InitialConnection ? "connect" : "reconnect";
final String transport = getName();
final String connectionToken = connection.getConnectionToken();
final String messageId = connection.getMessageId() != null ? connection.getMessageId() : "";
final String groupsToken = connection.getGroupsToken() != null ? connection.getGroupsToken() : "";
final String connectionData = connection.getConnectionData() != null ? connection.getConnectionData() : "";
String url = null;
try {
url = connection.getUrl() + "signalr/" + connectionString + '?' + "connectionData=" + URLEncoder.encode(URLEncoder.encode(connectionData, "UTF-8"), "UTF-8") + "&connectionToken=" + URLEncoder.encode(URLEncoder.encode(connectionToken, "UTF-8"), "UTF-8") + "&groupsToken=" + URLEncoder.encode(groupsToken, "UTF-8") + "&messageId=" + URLEncoder.encode(messageId, "UTF-8") + "&transport=" + URLEncoder.encode(transport, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mConnectionFuture = new UpdateableCancellableFuture<Void>(null);
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
mConnectionFuture.triggerError(e);
return mConnectionFuture;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
mConnectionFuture.setResult(null);
}
@Override
public void onMessage(String s) {
callback.onData(s);
}
@Override
public void onClose(int i, String s, boolean b) {
mWebSocketClient.close();
}
@Override
public void onError(Exception e) {
mWebSocketClient.close();
}
@Override
public void onFragment(Framedata frame) {
try {
String decodedString = Charsetfunctions.stringUtf8(frame.getPayloadData());
if (decodedString.equals("]}")) {
return;
}
if (decodedString.endsWith(":[") || null == mPrefix) {
mPrefix = decodedString;
return;
}
String simpleConcatenate = mPrefix + decodedString;
if (isJSONValid(simpleConcatenate)) {
onMessage(simpleConcatenate);
} else {
String extendedConcatenate = simpleConcatenate + "]}";
if (isJSONValid(extendedConcatenate)) {
onMessage(extendedConcatenate);
} else {
log("invalid json received:" + decodedString, LogLevel.Critical);
}
}
} catch (InvalidDataException e) {
e.printStackTrace();
}
}
};
mWebSocketClient.connect();
connection.closed(new Runnable() {
@Override
public void run() {
mWebSocketClient.close();
}
});
return mConnectionFuture;
}
Example 5
Project: KadecotCore-master File: KadecotWebsocketClientProxy.java View source code |
public void open(String ipaddress, String port) throws InterruptedException, TimeoutException {
if (mWsClient != null && mWsClient.getReadyState() == READYSTATE.OPEN) {
return;
}
URI uri;
try {
uri = new URI(PROTOCOL + ipaddress + ":" + port);
} catch (URISyntaxException e) {
Log.e(TAG, "URI Syntax Exception" + ipaddress);
return;
}
final CountDownLatch latch = new CountDownLatch(1);
mWsClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake handshakedata) {
latch.countDown();
}
@Override
public void onMessage(String message) {
try {
transmit(WampMessageFactory.create(new JSONArray(message)));
} catch (JSONException e) {
Log.e(TAG, "message is not WAMP format: " + message);
}
}
@Override
public void onError(Exception ex) {
Log.e(TAG, "onError : " + ex);
}
@Override
public void onClose(int code, String reason, boolean remote) {
transmit(WampMessageFactory.createGoodbye(new JSONObject(), WampError.SYSTEM_SHUTDOWN));
}
};
mWsClient.connect();
if (!latch.await(1, TimeUnit.SECONDS)) {
throw new TimeoutException("WebSocket connect timeout");
}
}
Example 6
Project: popcorn-android-master File: WebOSTVMouseSocketConnection.java View source code |
public void connectPointer(URI uri) {
if (ws != null) {
ws.close();
ws = null;
}
ws = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake arg0) {
Log.d("PtrAndKeyboardFragment", "connected to " + uri.toString());
if (listener != null) {
listener.onConnected();
}
}
@Override
public void onMessage(String arg0) {
}
@Override
public void onError(Exception arg0) {
}
@Override
public void onClose(int arg0, String arg1, boolean arg2) {
}
};
ws.connect();
}
Example 7
Project: plugin-socket.io-master File: WebSocket.java View source code |
protected void doOpen() {
if (!this.check()) {
return;
}
Map<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
this.emit(EVENT_REQUEST_HEADERS, headers);
final WebSocket self = this;
try {
this.ws = new WebSocketClient(new URI(this.uri()), new Draft_17(), headers, 0) {
@Override
public void onOpen(final ServerHandshake serverHandshake) {
EventThread.exec(new Runnable() {
@Override
public void run() {
Map<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
Iterator<String> it = serverHandshake.iterateHttpFields();
while (it.hasNext()) {
String field = it.next();
if (field == null)
continue;
headers.put(field, serverHandshake.getFieldValue(field));
}
self.emit(EVENT_RESPONSE_HEADERS, headers);
self.onOpen();
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
EventThread.exec(new Runnable() {
@Override
public void run() {
self.onClose();
}
});
}
@Override
public void onMessage(final String s) {
EventThread.exec(new Runnable() {
@Override
public void run() {
self.onData(s);
}
});
}
@Override
public void onMessage(final ByteBuffer s) {
EventThread.exec(new Runnable() {
@Override
public void run() {
self.onData(s.array());
}
});
}
@Override
public void onError(final Exception e) {
EventThread.exec(new Runnable() {
@Override
public void run() {
self.onError("websocket error", e);
}
});
}
};
//if (this.sslContext != null) {
// this.ws.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(this.sslContext));
//}
this.ws.connect();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
Example 8
Project: DeviceConnect-Android-master File: DConnectServerNanoHttpdTest.java View source code |
/** * DConnectServerNanoHttpdã‚’èµ·å‹•ã?—ã€?WebSocket通信を行ã?†ã€‚ * <pre> * ã€?期待ã?™ã‚‹å‹•ä½œã€‘ * ・DConnectServerNanoHttpdã?«WebSocketã?®æŽ¥ç¶šã?Œã?§ã??ã‚‹ã?“ã?¨ã€‚ * </pre> */ @Test public void DConnectServerNanoHttpd_websocket() { final CountDownLatch serverLaunchLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<String> result = new AtomicReference<>(); final String msg = "test-message"; File file = getContext().getFilesDir(); DConnectServerConfig config = new DConnectServerConfig.Builder().port(PORT).documentRootPath(file.getPath()).build(); DConnectServer server = new DConnectServerNanoHttpd(config, getContext()); server.setServerEventListener(new DConnectServerEventListener() { @Override public boolean onReceivedHttpRequest(final HttpRequest req, final HttpResponse res) { res.setCode(HttpResponse.StatusCode.OK); return true; } @Override public void onError(final DConnectServerError errorCode) { } @Override public void onServerLaunched() { serverLaunchLatch.countDown(); } @Override public void onWebSocketConnected(final DConnectWebSocket webSocket) { } @Override public void onWebSocketDisconnected(final DConnectWebSocket webSocket) { } @Override public void onWebSocketMessage(final DConnectWebSocket webSocket, final String message) { webSocket.sendMessage(message); } }); server.start(); try { serverLaunchLatch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("timeout"); } String uri = HTTP_LOCALHOST_PORT; WebSocketClient client = new WebSocketClient(URI.create(uri), new Draft_17(), null, 10000) { @Override public void onOpen(final ServerHandshake handshakedata) { send(msg); } @Override public void onMessage(final String message) { result.set(message); latch.countDown(); } @Override public void onClose(final int code, final String reason, final boolean remote) { } @Override public void onError(final Exception ex) { } }; client.connect(); try { boolean r = latch.await(10, TimeUnit.SECONDS); assertThat(r, is(true)); assertThat(result.get(), is(msg)); client.close(); } catch (InterruptedException e) { fail("timeout"); } finally { server.shutdown(); } }
Example 9
Project: relay-android-master File: SocketService.java View source code |
private boolean reconnect(final String host) {
URI uri;
try {
Log.i(TAG, host);
uri = new URI(host);
} catch (URISyntaxException e) {
e.printStackTrace();
return false;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i(TAG, "WS open");
mDirtyLoop.run();
}
@Override
public void onMessage(String message) {
int pos = message.indexOf(" ");
String name = pos == -1 ? message : message.substring(0, pos);
String data = pos == -1 ? null : message.substring(pos + 1);
Log.i(TAG, "WS Message: " + name);
switch(name) {
case "client:listSMS":
getSMS(data);
break;
case "client:listContacts":
getContacts();
break;
case "client:sendText":
Log.i(TAG, data);
sendText(data);
break;
}
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i(TAG, "WS close: " + s);
mDirtyLooper.removeCallbacks(mDirtyLoop);
// TODO: Exponential back-off/rediscovery
reconnect(host);
}
@Override
public void onError(Exception e) {
Log.i(TAG, "WS onError");
e.printStackTrace();
}
};
mWebSocketClient.connect();
return true;
}
Example 10
Project: appengine-websocketchat-java-master File: ChatSocketServer.java View source code |
/** * Propagate a message popped from the propagateQueue to other active server nodes. * * @throws IOException */ private void propagateOneMessage() throws IOException { if (!chatSocketServer.propagateQueue.isEmpty()) { // handle message propagation between the server nodes. OutgoingMessage message = chatSocketServer.propagateQueue.remove(); LOG.info("Handling a propagate message: " + message.toJson(GSON)); Key<WebSocketServerNode> parentKey = WebSocketServerNode.getRootKey(); List<Key<WebSocketServerNode>> serverKeys = ofy().load().type(WebSocketServerNode.class).ancestor(parentKey).keys().list(); final ChatMessage propagateMessage = ChatMessage.createPropagateMessage(message, GSON); for (Key<WebSocketServerNode> key : serverKeys) { LOG.info("Server: " + key.getName()); if (!key.getName().equals(chatSocketServer.getWebSocketURL())) { // Send a propagate message LOG.info("Trying to send a message to the server: " + key.getName()); try { final WebSocketClient chatClient = new WebSocketClient(new URI(key.getName())) { @Override public void onOpen(ServerHandshake handshakedata) { // Send propagateMessage itself. this.send(GSON.toJson(propagateMessage)); this.close(); } @Override public void onMessage(String message) { LOG.info("Message received: " + message); } @Override public void onClose(int code, String reason, boolean remote) { LOG.info("Connection closed."); } @Override public void onError(Exception ex) { LOG.warning(Throwables.getStackTraceAsString(ex)); } }; chatClient.connect(); } catch (URISyntaxException e) { LOG.warning(Throwables.getStackTraceAsString(e)); } } } } }
Example 11
Project: quhao-master File: MerchantChatActivity.java View source code |
private void connectWebSocket() {
URI uri = null;
try {
String userName = URLEncoder.encode(user, "UTF-8");
String imageUrl = URLEncoder.encode(image, "UTF-8");
String url = "ws://www.quhao.la:" + port + "/websocket/room/socket?uid=" + uid + "&image=" + imageUrl + "&mid=" + mid + "&user=" + userName;
Log.e(LOGTAG, url);
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.e("Websocket", "Opened");
// mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String s) {
Log.e("wjzwjz", s);
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (null == chats) {
chats = new ArrayList<ChatVO>();
}
ChatVO chat = null;
if (StringUtils.isNotNull(message)) {
if (!message.startsWith("join") && !message.startsWith("leave")) {
// 消�类型:昵称:用户ID:头�:消�内容
String[] strs = message.split(":");
String type = strs[0];
// Date date = new Date(Long.valueOf(strs[1]));
String name = strs[1];
String userId = strs[2];
String userImage = QuhaoConstant.HTTP_URL.substring(0, QuhaoConstant.HTTP_URL.length() - 1) + strs[3];
String msg = strs[4];
if (strs.length > 5) {
for (int i = 4; i < strs.length; i++) {
if (i == strs.length - 1) {
msg = msg + strs[i];
continue;
}
msg = strs[i] + ":";
}
}
//ws://www.quhao.la:9000/websocket/room/socket?uid=uid1&image=image1&mid=mid1&user=11
String msgFrom = "server";
if (uid.equals(userId)) {
msgFrom = "client";
}
chat = new ChatVO(type, name, userId, userImage, msg, msgFrom);
chats.add(chat);
}
if (chatAdapter == null) {
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.no_logo).showImageForEmptyUri(R.drawable.no_logo).showImageOnFail(R.drawable.no_logo).cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).displayer(new RoundedBitmapDisplayer(20)).build();
chatAdapter = new MerchantChatAdapter(MerchantChatActivity.this, chatListView, chats, options, new AnimateFirstDisplayListener());
chatListView.setAdapter(chatAdapter);
} else {
chatAdapter.chats = chats;
}
chatAdapter.notifyDataSetChanged();
}
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.e("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.e("Websocket", "Error " + e.getMessage());
this.connect();
}
};
mWebSocketClient.connect();
}
Example 12
Project: aphelion-master File: WebSocketTransport.java View source code |
@Override
public /** Do a single loop to update internal state.
* NOTE: when using any of the close() functions make sure loop() is called at least once before
* forgetting about this object.
*/
void loop(long systemNanoTime, long unused) {
// do not use unused (this method is not just called by TickedEventLoop)
synchronized (this.serverUnitializedWebsockets) {
Iterator<WebSocket> it = this.serverUnitializedWebsockets.iterator();
while (it.hasNext()) {
WebSocket ws = it.next();
WebSocketData wsd = WebSocketData.get(ws);
if (systemNanoTime - wsd.openedAt > SERVER_INIT_TIMEOUT) {
log.log(Level.WARNING, "Dropped unitialized websocket as a server ({0}) due to timeout ({1} nanoseconds). ", new Object[] { ws.getRemoteSocketAddress(), systemNanoTime - wsd.openedAt });
close(ws, WS_CLOSE_STATUS.INIT_TIMEOUT);
it.remove();
}
}
}
synchronized (this.unitializedClients) {
Iterator<MyWebSocketClient> it = this.unitializedClients.iterator();
while (it.hasNext()) {
MyWebSocketClient client = it.next();
if (systemNanoTime - client.openedAt > CLIENT_CONNECT_TIMEOUT) {
log.log(Level.WARNING, "Dropped unitialized websocket as a client due to timeout ({0} nanoseconds).", systemNanoTime - client.openedAt);
// this will fail if the thread spawned by WebSocketClient;
// has not had a chance to run yet.
close(client.getConnection(), WS_CLOSE_STATUS.INIT_TIMEOUT);
it.remove();
}
}
}
CloseDTO closeDto;
while ((closeDto = closeQueue.poll()) != null) {
// may generate an event immediately, which this class listens to
closeDto.ws.close(closeDto.code.id, closeDto.message);
}
}
Example 13
Project: intellij-community-master File: IpnbConnection.java View source code |
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();
}
Example 14
Project: Protocoder-master File: PNetwork.java View source code |
@ProtocoderScript @APIMethod(description = "Connect to a websocket server", example = "") @APIParam(params = { "uri", "function(status, data)" }) public WebSocketClient connectWebsocket(String uri, final connectWebsocketCB callbackfn) { Draft d = new Draft_17(); WebSocketClient webSocketClient = null; try { webSocketClient = new WebSocketClient(new URI(uri), d) { @Override public void onOpen(ServerHandshake arg0) { mHandler.post(new Runnable() { @Override public void run() { callbackfn.event("onOpen", ""); } }); //Log.d(TAG, "onOpen"); } @Override public void onMessage(final String arg0) { mHandler.post(new Runnable() { @Override public void run() { callbackfn.event("onMessage", arg0); } }); //Log.d(TAG, "onMessage client"); } @Override public void onError(Exception arg0) { mHandler.post(new Runnable() { @Override public void run() { callbackfn.event("onError", ""); } }); //Log.d(TAG, "onError"); } @Override public void onClose(int arg0, String arg1, boolean arg2) { mHandler.post(new Runnable() { @Override public void run() { callbackfn.event("onClose", ""); } }); //Log.d(TAG, "onClose"); } }; webSocketClient.connect(); } catch (URISyntaxException e) { Log.d(TAG, "error"); callbackfn.event("error ", e.toString()); e.printStackTrace(); } return webSocketClient; }