Use this library org.java_websocket
The first thing you should import this library into build.gradle
repositories { mavenCentral() }
then add the implementation to the {} dependency
implementation "org.java-websocket:Java-WebSocket:1.3.0"
Then you can use this code
In your activity, declare an object for the Websocketclient as
private WebSocketClient mWebSocketClient;
then add this method to callback
private void ConnectToWebSocket() { URI uri; try { uri = new URI("ws://your web socket url"); } catch (URISyntaxException e) { e.printStackTrace(); return; } mWebSocketClient = new WebSocketClient(uri) { @Override public void onOpen(ServerHandshake serverHandshake) { Log.i("Websocket", "Opened"); mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL); } @Override public void onMessage(String s) { final String message = s; runOnUiThread(new Runnable() { @Override public void run() { TextView textView = (TextView)findViewById(R.id.edittext_chatbox); textView.setText(textView.getText() + "\n" + message); } }); } @Override public void onClose(int i, String s, boolean b) { Log.i("Websocket", "Closed " + s); } @Override public void onError(Exception e) { Log.i("Websocket", "Error " + e.getMessage()); } }; mWebSocketClient.connect();
}
Muhammed Fasil Jun 20 '18 at 8:35 2018-06-20 08:35
source share