Android websocket stream video playback - android

How to playback video stream from web socket address like :
ws://somevideserver.net:8410/5b03a7aad01502281a39?
I tried using WebSocketClient and successfully connect to port, but how to retrieve stream and send it to player?
URI uri;
try {
uri = new URI(stremURL);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.d(TAG, "[getStreamURL] = "+"Opened");
// mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
startStreaming();
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "[getStreamURL] message = "+message);
}
});
}
private void runOnUiThread(Runnable websocket) {
}
#Override
public void onClose(int i, String s, boolean b) {
Log.d(TAG, "[getStreamURL] = "+"Closed");
}
#Override
public void onError(Exception e) {
Log.d(TAG, "[getStreamURL] = "+"Error");
}
};
mWebSocketClient.connect();

Related

Connect to several Mqtt servers using paho.mqtt.android

Can this library give opportunity make connections for several servers?
https://github.com/eclipse/paho.mqtt.android
I can not figure this case out the source code
For example:
mqttAndroidClient1 = new MqttAndroidClient(getApplicationContext(), "tcp://iot.eclipse.org:1883", clientId);
mqttAndroidClient2 = new MqttAndroidClient(getApplicationContext(), "tcp://iot.blablabla.org:1883", clientId);
....
mqttAndroidClient1.connect(...)
mqttAndroidClient2.connect(...)
Ok. It's work. I tested through my locale device and this service https://iot.eclipse.org/getting-started#sandboxes.
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Handler mHandler = new Handler();
MqttAndroidClient mqttAndroidClient1;
MqttAndroidClient mqttAndroidClient2;
String clientId = "ExampleAndroidClient";
final String serverUri = "tcp://iot.eclipse.org:1883";
final String serverUri2 = "tcp://192.168.10.11:1883" ;
#Override
protected void onStart() {
super.onStart();
clientId = clientId + System.currentTimeMillis();
mqttAndroidClient2 = new MqttAndroidClient(getApplicationContext(), serverUri2, clientId+"2");
mqttAndroidClient2.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String serverURI) {
if (reconnect) {
Log.i(TAG,"Reconnected to : " + serverURI);
// Because Clean Session is true, we need to re-subscribe
subscribeToTopic2();
} else {
Log.i(TAG,"Connected to: " + serverURI);
}
}
#Override
public void connectionLost(Throwable cause) {
Log.w(TAG,"The Connection was lost.");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG,"Incoming message: " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
mqttAndroidClient1 = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
mqttAndroidClient1.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String serverURI) {
if (reconnect) {
Log.i(TAG,"Reconnected to : " + serverURI);
// Because Clean Session is true, we need to re-subscribe
subscribeToTopic1();
} else {
Log.i(TAG,"Connected to: " + serverURI);
}
}
#Override
public void connectionLost(Throwable cause) {
Log.w(TAG,"The Connection was lost.");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG,"Incoming message: " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
try {
//addToHistory("Connecting to " + serverUri);
mqttAndroidClient1.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient1.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic1();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e(TAG,"Failed to connect to: " + mqttAndroidClient1.getServerURI());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
try {
//addToHistory("Connecting to " + serverUri);
mqttAndroidClient2.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient2.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic2();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e(TAG,"Failed to connect to: " + mqttAndroidClient2.getServerURI());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
}
public void subscribeToTopic1(){
String subscriptionTopic = "/uwblogs";
try {
mqttAndroidClient1.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG,"Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.i(TAG,"Failed to subscribe");
}
});
mqttAndroidClient1.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// message Arrived!
final String str = new String(message.getPayload());
mHandler.post(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView_server1)).setText(str);
}
});
Log.i(TAG,"Message: " + topic + " : " + new String(message.getPayload()));
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
public void subscribeToTopic2(){
String subscriptionTopic = "/devices/wb-adc/controls/Vin";
try {
mqttAndroidClient2.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG,"Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.i(TAG,"Failed to subscribe");
}
});
mqttAndroidClient2.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// message Arrived!
final String str = new String(message.getPayload());
mHandler.postAtFrontOfQueue(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView_server2)).setText(str);
}
});
Log.i(TAG,"Message server2: " + topic + " : " + new String(message.getPayload()));
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
}

Android MQTT async subscribe

I just start use MQTT Paho library in my app.
How to make an asynchronous subscription to the topic? (subscription in new thread)
And then in real time to receive the data and display.
It's my code in MainActivity, in main thread:
public void mqttConnect () {
final TextView textView = (TextView) findViewById(R.id.sub_Text_View);
String clientId = MqttClient.generateClientId();
final MqttAndroidClient client = new MqttAndroidClient(this.getApplicationContext(), server, clientId);
client.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean reconnect, String serverURI) {
}
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d("NANADEV", message.toString());
textView.setText(message.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
try {
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
final String topic = "testwork/value";
int qos =0;
try {
IMqttToken subToken = client.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
Thanks!
In your oncreate
private String uniqueID;
String ip="brokerip";
String port="brokerport usaly 1883"
String broker = "tcp://" + ip + ":" + port;
uniqueID = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
IMqttAsyncClient client= new MqttAsyncClient(broker, uniqueID, new MemoryPersistence());
mqttClient.subscribe("YOURTOPIC/", 0);
mqttClient.subscribe("YOUROTHERTOPIC", 0);
and then in your method:
public void messageArrived(String topic, MqttMessage msg) throws Exception {
Log.i("mqttarrival", "Message arrived from topic " + topic);
if (topic.equals("YOURTOPIC")) {
System.out.println(msg.toString());
}
else {
}
}

Why websocket from AndroidAsync always null

I'm developing a simple WebSocket in Android using AndroidAsync library:
http://www.koushikdutta.com/AndroidAsync
My Client code:
private void conectar() {
//String uri = "ws://192.167.101.142:1234";
String uri = "http://192.167.101.166:1234";
AsyncHttpClient asyncHttpClient = AsyncHttpClient.getDefaultInstance();
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "my-protocol", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(uri, "https", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), null, new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "SSL", new AsyncHttpClient.WebSocketConnectCallback() {
asyncHttpClient.websocket(uri, null, new AsyncHttpClient.WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
Log.e(TAG, "webSocket is null");
Log.e(TAG, "Metodo onCompleted");
if (ex != null) {
Log.e(TAG, ex.getMessage(), ex);
return;
}
//Log.e(TAG, "webSocket.isOpen(): " + webSocket.isOpen());
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new WebSocket.StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
Log.e(TAG, "I got a string: " + s);
//showToast("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
#Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
Log.e(TAG, "I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
}
My Server code:
private void conectar() {
AsyncHttpServer server = new AsyncHttpServer();
server.listen(PORTA);
server.get("/", new HttpServerRequestCallback() {
#Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("Hello!!!");
}
});
server.websocket("/", new AsyncHttpServer.WebSocketRequestCallback() {
#Override
public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
Log.e(TAG, "Metodo: onConnected");
_sockets.add(webSocket);
//Use this to clean up any references to your websocket
webSocket.setClosedCallback(new CompletedCallback() {
#Override
public void onCompleted(Exception ex) {
Log.e(TAG, "Metodo onCompleted from webSocket object");
try {
if (ex != null)
Log.e("WebSocket", "Error");
} finally {
_sockets.remove(webSocket);
}
}
});
webSocket.setStringCallback(new WebSocket.StringCallback() {
#Override
public void onStringAvailable(String s) {
Log.e(TAG, "Metodo onStringAvailable from webSocket object");
if ("Hello Server".equals(s))
webSocket.send("Welcome Client!");
}
});
}
});
Anyone knows tell me why Can't I connect my server?
I have tested the server code in another app websocket tester from google play.
The app server it's Ok.
However I cannot connect from my client app?

Android Autobahn request.getHttpSession() = null

Client side code:
private void startPolling() {
final String wsuri = MainAsync.WEB_SOCKET_HOST_WS+"/game";
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri);
int role = mAccMeth.loadId(getApplicationContext());
mConnection.sendTextMessage(String.valueOf(role));
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection lost.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
Server side realisation:
#ServerEndpoint(value="/game",configurator = ServletConfig.class)
public class WebSocketPollingCoordinates {
EndpointConfig endConfig;
#OnMessage
public void receiveMessage(String message,final Session session){
HttpSession httpSession = (HttpSession) endConfig.getUserProperties().get("httpSession");
//at this line i get NullpointerException
final ServletContext sercntxt = (ServletContext)httpSession.getServletContext();
}
#OnOpen
public void onOpen(Session sn, EndpointConfig ec) {
System.out.println("onOpen");
this.endConfig = ec;
}
#OnError
public void error(Session session, Throwable t) {
t.printStackTrace();
}
And WebSocket Config class:
public class ServletConfig extends Configurator{
#Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
if(httpSession==null || config==null){
if(httpSession==null)
System.out.println("httpSession==null");
if(config==null)
System.out.println("config==null");
return;
}
config.getUserProperties().put("httpSession", httpSession);
}
}
I'm always getting next out: http session == null. Where is the error? I need to get httpSession, to call void httpSession.getServletContext();

Android - Autobahn Websocket sending message error(NullPointerException)

I am working on websocket communication with Autobahn.
On the main.class of my app, I set to call 'connect()' when users click a button.
// Toggle Button event
tButton = (ToggleButton) findViewById(R.id.toggleButton1);
tButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
}else{
}
}
});
And after that, there is MyOffers.class, and if this class is accessed,
MyOffers_Fragment class is produced four times automatically, because MyOffers.class contains 'carousel view' and there are four products.
On 'MyOffers_Fragment' class, when users click one of the image of products, message should be sent.
if (pos == 0) {
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setOnClickListener(new ImageButton.OnClickListener(){
public void onClick(View v){
String id = "Product0";
Log.d(TAG, "Current product is : " + id);
A.sendMessage(id);
}
});
}
But 'mConnection.sendTextMessage(id1);' this line makes 'NullPointerException' error.
There is a class 'Websocket_Connector.class'
public class WebSocket_Connector {
private static final String TAG = "ECHOCLIENT";
public final WebSocketConnection mConnection = new WebSocketConnection();
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
public void sendMessage(String message) {
connect("ws://192.168.x.xxx:xxxx");
mConnection.sendTextMessage(message);
}
}
I called 'connect()' in the main page class, and after that try to send message.
But, it's not working..Can you please help me out?
public class WebSocket_Connector {
private static final String TAG = "ECHOCLIENT";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
public void sendMessage(String message) {
if (mConnection.isConnected())
mConnection.sendTextMessage(message);
else {
tmpString = message;
connect("ws://192.168.x.xxx:xxxx");
}
}
}

Categories

Resources