autobahn not working with tomcat 7 websocket - android

Sorry for my english.
I want to program a native app in Android to connect with a server for interactive comunications. Websocket tegnology is perfect fothis. I have installed and working Tomcat 7.0.39 in my laptop with IP 192.168.1.250. I have tryed the examples echo, snake, etc and it works fine using ws://localhost:8080/.... and using ws://192.168.1.250:8080/...
I'm using autobahn with eclipse to connect to my server. I have installed apk in my Android mobile with autobahn client websocket sample and it connects perfectly withn ws://echo.websocket.org.
The problem is that from android to my server (in my laptop) not work. From android to ws://echo.websocket.org works fine (I supose that autobahn example works well), my server works fine because de examples comes with tomcat work fine.
Because I have to make intesive work with information that travel between server and clients, I can't use javascript on server side, I need java servlets or others to work with databases, files ando so on.
What is wrong? Firewall is off, and wireshark show me how android client try to connect to my laptop server ( I don't anderstand wireshark info well ) but the connection loses.
This my android code:
package com.example.autobahnandroiddemo;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
static final String TAG = "de.tavendo.autobahn.echo";
private static final String PREFS_NAME = "AutobahnAndroidEcho";
static EditText mHostname;
static EditText mPort;
static TextView mStatusline;
static Button mStart;
static EditText mMessage;
static Button mSendMessage;
private SharedPreferences mSettings;
private void alert(String message) {
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
private void loadPrefs() {
mHostname.setText(mSettings.getString("hostname", ""));
mPort.setText(mSettings.getString("port", "9000"));
}
private void savePrefs() {
SharedPreferences.Editor editor = mSettings.edit();
editor.putString("hostname", mHostname.getText().toString());
editor.putString("port", mPort.getText().toString());
editor.commit();
}
private void setButtonConnect() {
mHostname.setEnabled(true);
mPort.setEnabled(true);
mStart.setText("Connect");
mStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
start();
}
});
}
private void setButtonDisconnect() {
mHostname.setEnabled(false);
mPort.setEnabled(false);
mStart.setText("Disconnect");
mStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mConnection.disconnect();
}
});
}
private final WebSocketConnection mConnection = new WebSocketConnection();
private void start() {
final String wsuri = mHostname.getText() + ":" + mPort.getText();
mStatusline.setText("Status: Connecting to " + wsuri + " ..");
setButtonDisconnect();
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
mStatusline.setText("Status: Connected to " + wsuri);
savePrefs();
mSendMessage.setEnabled(true);
mMessage.setEnabled(true);
}
#Override
public void onTextMessage(String payload) {
alert("Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
alert("Connection lost.");
mStatusline.setText("Status: Ready.");
setButtonConnect();
mSendMessage.setEnabled(false);
mMessage.setEnabled(false);
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHostname = (EditText) findViewById(R.id.hostname);
mPort = (EditText) findViewById(R.id.port);
mStatusline = (TextView) findViewById(R.id.statusline);
mStart = (Button) findViewById(R.id.start);
mMessage = (EditText) findViewById(R.id.msg);
mSendMessage = (Button) findViewById(R.id.sendMsg);
mSettings = getSharedPreferences(PREFS_NAME, 0);
loadPrefs();
setButtonConnect();
mSendMessage.setEnabled(false);
mMessage.setEnabled(false);
mSendMessage.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mConnection.sendTextMessage(mMessage.getText().toString());
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mConnection.isConnected()) {
mConnection.disconnect();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.quit:
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
AND THIS IS MY SERVLET TOMCAT CODE:
package servlets;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class SimpleWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
#Override
protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr) {
return new MessageInbound() {
#Override
protected void onBinaryMessage(ByteBuffer bb) throws IOException {
}
#Override
protected void onTextMessage(CharBuffer cb) throws IOException {
System.out.println(cb.toString());
WsOutbound outbound = getWsOutbound();
outbound.writeTextMessage(cb);
}
};
}
}
I don't know what's wrong. Have another solution to use android client in conjuntion with server (java servlets on similar tecnology) through websockets?
Thanks

I think you should have put the code of connecting into onCreate.

Related

Bluetooth app made with library (https://github.com/OmarAflak/Bluetooth-Library) crashes

I'm working on a simple app, essentially to send data over Bluetooth.
My MainActivity:
package in.justrobotics.jrbluetoothcontrol;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import me.aflak.bluetooth.Bluetooth;
import me.aflak.bluetooth.BluetoothCallback;
import me.aflak.bluetooth.DiscoveryCallback;
public class MainActivity extends AppCompatActivity {
Bluetooth bluetooth;
private ArrayAdapter<String> mBTArrayAdapter;
String address,name;
public void composeEmail(String message) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] { "shlokj#gmail.com" });
intent.putExtra(Intent.EXTRA_SUBJECT, "Would like to get in touch");
intent.putExtra(Intent.EXTRA_TEXT, message);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
public void sendEmail () {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Send a message: ");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String Message = input.getText().toString();
composeEmail(Message);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothOn();
mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
bluetooth = new Bluetooth(getApplicationContext());
if (bluetooth==null){
Toast.makeText(getApplicationContext(),"Bluetooth null",Toast.LENGTH_SHORT).show();
}
if (bluetooth!=null){
Toast.makeText(getApplicationContext(),"Bluetooth not null",Toast.LENGTH_SHORT).show();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
Button openController = (Button) findViewById(R.id.open_controller);
openController.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startController = new Intent(MainActivity.this,ControllerActivity.class);
//startController.putExtra("BLUETOOTH_CONNECTED_THREAD",mConnectedThread);
startActivity(startController);
}
});
Button openAccelController = (Button) findViewById(R.id.open_accel_controller);
openAccelController.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startControllerAccel = new Intent(MainActivity.this,AccelerometerControl.class);
startActivity(startControllerAccel);
}
});
bluetooth.setBluetoothCallback(new BluetoothCallback() {
#Override
public void onBluetoothTurningOn() {
}
#Override
public void onBluetoothOn() {
}
#Override
public void onBluetoothTurningOff() {
}
#Override
public void onBluetoothOff() {
}
#Override
public void onUserDeniedActivation() {
}
});
bluetooth.setDiscoveryCallback(new DiscoveryCallback() {
#Override public void onDiscoveryStarted() {}
#Override public void onDiscoveryFinished() {}
#Override public void onDeviceFound(BluetoothDevice device) {}
#Override public void onDevicePaired(BluetoothDevice device) {}
#Override public void onDeviceUnpaired(BluetoothDevice device) {}
#Override public void onError(String message) {}
});
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.dialog_btdevices, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select your device");
alertDialog.setMessage("A JR Bluetooth device name is of the form JR_X");
ListView devicesListView = (ListView) convertView.findViewById(R.id.mDevicesListView);
devicesListView.setAdapter(mBTArrayAdapter);
devicesListView.setOnItemClickListener(mDeviceClickListener);
alertDialog.show();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
String connectStatus="";
if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
return;
}
//mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
name = info.substring(0, info.length() - 17);
if (bluetooth.isConnected()){
connectStatus="Connected";
}
if (!bluetooth.isConnected()){
connectStatus="Not connected";
}
Toast.makeText(getBaseContext(), connectStatus, Toast.LENGTH_SHORT).show();
bluetooth.connectToAddress(address);
Toast.makeText(getBaseContext(), "Connected (hopefully)", Toast.LENGTH_SHORT).show();
bluetooth.send("test");
Toast.makeText(getBaseContext(), "Sent data (hopefully)", Toast.LENGTH_SHORT).show();
}};
#Override
protected void onStart() {
super.onStart();
bluetooth.onStart();
bluetooth.enable();
}
#Override
protected void onStop() {
super.onStop();
bluetooth.onStop();
}
private void bluetoothOn(){
if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
//mBluetoothStatus.setText("Bluetooth enabled");
Toast.makeText(getApplicationContext(),"Bluetooth turned on",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
}
}
}
Stack traces:
2019-04-09 20:16:48.222 23737-23737/in.justrobotics.jrbluetoothcontrol E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.justrobotics.jrbluetoothcontrol, PID: 23737
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
at me.aflak.bluetooth.Bluetooth.send(Bluetooth.java:185)
at me.aflak.bluetooth.Bluetooth.send(Bluetooth.java:201)
at in.justrobotics.jrbluetoothcontrol.MainActivity$7.onItemClick(MainActivity.java:197)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1164)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3154)
at android.widget.AbsListView$3.run(AbsListView.java:4097)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
The custom Bluetooth class: https://github.com/OmarAflak/Bluetooth-Library/blob/master/bluetooth/src/main/java/me/aflak/bluetooth/Bluetooth.java
My code is crashing at the line bluetooth.send("test"); with a NullPointerException, and I can't see why. I'm a beginner with Bluetooth on Android; help will be appreciated.
The final outcome I hope I will be able to get is to simply connect to a device and send data, and even that isn't happening.
Edit: I'm facing another problem as well now. I pass the String address to the second activity (https://gist.github.com/shlokj/12c4e2c62ca0f5284c5c3c041775654f) from the first activity (https://gist.github.com/shlokj/f80d0902ad1a366ab03e178164968cfb) through an intent. There, I try to connect at line 163 (bluetoothObject.connectToAddress(address);), and it crashes with a NullPointerException. I have no idea why, because I check that the Bluetooth object and address are not null with an if statement. Stack traces: https://gist.github.com/shlokj/56e3c9e311dea6f77a1acd8953a317c8 Whole repository: https://github.com/shlokj/JR-Bluetooth-Control.
So, in a nutshell, I now need to be also able to connect properly, leave alone sending data.
I just went through the library link you provided and it seems someone else faced the similar issue given here:
https://github.com/OmarAflak/Bluetooth-Library/issues/16
And it turned out be the connection wasn't established yet,so before calling send please check if the device is connected by using isConnected() function.
You shouldn't call send before the connection is established properly.you can set callback for the same using setDiscoveryCallback and do work inside most probable after you get confirmation in void onDevicePaired(BluetoothDevice device).
Edit 1: from the comments.
Are you sure it is in onDevicePaired() that I am supposed to send
data?
Maybe not,I think i misunderstood the example given by library author,now i think you should do it on onDeviceConnected.
Is there any other method that gets called when it is connected?
Yes,you can set a callback for that using following:
bluetooth.setDeviceCallback(new DeviceCallback() {
#Override
public void onDeviceConnected(BluetoothDevice device) {
// do your work here.
}
#Override
public void onDeviceDisconnected(BluetoothDevice device, String message) {
}
#Override
public void onMessage(String message) {
}
#Override
public void onError(String message) {
}
#Override
public void onConnectError(BluetoothDevice device, String message) {
}
});
Edit 2:
There, I try to connect at line
163(bluetoothObject.connectToAddress(address);), and it crashes with a
NullPointerException.
This crash happens because BluetoothAdapter isn't initialized yet,so when you call bluetoothObject.connectToAddress(address) it throws NullPointerException.
You need to initialize that before connecting as following:
bluetoothObject = new Bluetooth(getApplicationContext());
bluetoothObject.onStart();//this is the line that initializes adapter.
bluetoothObject.enable();

How to receive Messages in chat App using signalR in Android

hello i am new in signalR i am making one chating app with using signalR i take reference from SignalR integration in android studio here with the help of this i able to send the messages to the chat group but i am not able to receive messages i read lots of Q&A here but i am not able to solve this problem i paste here my code and please anyone tell me how do i receive message from the server.following is my code.
Activity main
package myapp.chatapp;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
public class MainActivity extends AppCompatActivity implements SignalRService.Something {
private StringBuilder mLog;
private ListView mTestCaseList;
private Spinner mTestGroupSpinner;
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private final Context mContext = this;
private SignalRService mService;
private SignalRService mMessageResive;
private boolean mBound = false;
ListView list_item;
EditText editText;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ClientTransport transport;
private Handler mHandler; // to display Toast message
private Thread t;
#Override
public void onConfigurationChanged(Configuration newConfig) {
// don't restart the activity. Just process the configuration change
super.onConfigurationChanged(newConfig);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClass(mContext, SignalRService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
editText = (EditText)findViewById(R.id.edit_message);
ImageButton btn = (ImageButton)findViewById(R.id.btn);
list_item = (ListView)findViewById(R.id.list_item);
listItems = new ArrayList<String>();
/*listItems.add("First Item - added on Activity Create");*/
/* adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);*/
adapter = new ArrayAdapter<String>(mContext,R.layout.custom_list, R.id.textView,listItems);
list_item.setAdapter(adapter);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 1000 );
}
}, 1000 );
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
sendMessage(view);
}
});
}
#Override
protected void onStop() {
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
public void sendMessage(View view) {
if (mBound) {
String message = editText.getText().toString();
String email = "kn#yopmail.com";
String name = "Kunal From Android";
String group ="1";
mService.sendMessage(name,email,group,message);
editText.setText("");
// Call a method from the SignalRService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
/*EditText editText = (EditText) findViewById(R.id.edit_message);
if (editText != null && editText.getText().length() > 0) {
}*/
}
}
public void setmMessageResive(JsonElement jsonElement)
{
listItems.add(10, String.valueOf(jsonElement));
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// We've bound to SignalRService, cast the IBinder and get SignalRService instance
SignalRService.LocalBinder binder = (SignalRService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
public void doSomething(String msg) {
listItems.add(msg);
}
}
Service code
package myapp.chatapp;
import android.app.Service;
import android.bluetooth.BluetoothClass;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import microsoft.aspnet.signalr.client.Action;
import microsoft.aspnet.signalr.client.Credentials;
import microsoft.aspnet.signalr.client.LogLevel;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.Request;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler4;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
/**
* Created by NULLPLEX7 on 11/28/2017.
*/
public class SignalRService extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder(); // Binder given to clients
ClientTransport transport;
registerListener registerListener;
private MainActivity setmMessageResive;
public Something list;
public SignalRService() {
}
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Return the communication channel to the service.
startSignalR();
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public SignalRService getService() {
// Return this instance of SignalRService so clients can call public methods
return SignalRService.this;
}
}
/**
* method for clients (activities)
*/
public void sendMessage(String name, String email, String group, String msg ) {
String SERVER_METHOD_SEND = "BroadCastMessage";
mHubProxy.invoke(SERVER_METHOD_SEND, name,email,group,msg);
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
Credentials credentials = new Credentials() {
#Override
public void prepareRequest(Request request) {
request.addHeader("User-Name", "BNK");
}
};
String serverUrl = "myurlhere";
mHubConnection = new HubConnection(serverUrl);
mHubConnection.setCredentials(credentials);
String SERVER_HUB_CHAT = "ChatHub";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
mHubProxy.subscribe(this);
transport = new LongPollingTransport(mHubConnection.getLogger());
mHubConnection.start(transport);
/* ****new codes here**** */
/* ****seems useless but should be here!**** */
mHubProxy.subscribe(new Object() {
#SuppressWarnings("unused")
public void newMessage(final String message, final String messageId, final String chatId,
final String senderUserId, final String fileUrl, final String replyToMessageId) {
}
});
try {
signalRFuture.get();
}catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return;
}
mHubProxy.on("receiveGroupMessage",
new SubscriptionHandler4<String, String, String, String>() {
#Override
public void run(final String name,final String msg ,final String avtar,final String date ) {
final String finalMsg = name + " says " + msg;
/*final String finalMsg = msg;*/
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
list.doSomething(msg);
}
});
}
}
, String.class,String.class,String.class,String.class);
mHubConnection.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(final JsonElement json) {
Log.e("receiveGroupMessage ", json.toString());
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ""+json, Toast.LENGTH_SHORT).show();
}
});
}
});
}
public interface Something
{
void doSomething(String msg);
}
}
i read on stack overflow that in onMessageReceived i get the server responses but i did not get any response here . I want when any one send message in group from web i want that message in my chat app someone suggest me that i need to create Event listener but i don't no how to create it . please tell me how do i get messages in my chat app.
mHubProxy.on("receiveGroupMessage",
new SubscriptionHandler4<String, String, String, String>() {
#Override
public void run(final String name,final String msg ,final String avtar,final String date ) {
final String finalMsg = name + " says " + msg;
/*final String finalMsg = msg;*/
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
list.doSomething(msg);
}
});
}
}
, String.class,String.class,String.class,String.class);
i thought that i got messages here but execution not go inside the Run.
Any Help is Welcome

Is LocalBroadcastReceiver + IntentService the correct practice?

I am trying to understand how this stuff works a little better.
So I learned about Runnables and Threads and ASyncTasks but apparently they have some serious drawbacks when it comes to configuration changes like rotating the screen.
Is it better to instead use IntentService for anything that should run in the background like SQL database commands, file-system procedures, Internet input/output processes, etc -- and then use LocalBroadcastReceiver to pass results back to the Activity?
Is it better to instead use IntentService for anything that should run in the background like SQL database commands, file-system procedures, Internet input/output processes, etc -- and then use LocalBroadcastReceiver to pass results back to the Activity?
A service is needed if your UI might move to the background while the work is going on, and you are concerned that your process might be terminated while the work is going on. I tend to only worry about this if the work might exceed a second or so. Otherwise, a plain thread suffices.
Using an event bus, like LocalBroadcastManager, is a reasonable approach to let other components know when your service/thread is done with its work. This sample app demonstrates this. Personally, I tend to use greenrobot's EventBus — this sample app is a clone of the first one, but using EventBus instead of LocalBroadcastManager.
Follow an example of a chat using one activity (chat activity) that run a class in service (realtime class). I use a mvc webapi to controll chat between chatters. When realtime receive a message "onConnected" or "ReceivedMessageServer" automatically send by LocalBroadcastManager to chat activity. This way in "onReceive" from BroadcastReceiver receives the message and runs other tasks.
a) ChatActivity.class
package br.com.yourapp;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
import br.com.yourapp.model.MessageReceived;
import util.RealTime;
public class ChatActivity extends AppCompatActivity implements View.OnClickListener,
View.OnKeyListener , TextWatcher {
AppController obj;
private ProgressDialog pDialog;
MediaPlayer mp;
private ListView lstChatLog;
private ArrayAdapter<String> listAdapter;
private EditText txtChatMessage;
private TextView lblTyping;
private Button btnSendChat;
private boolean resultRequest = true;
private String errorMessage = "Internet is not working";
private AlertDialog alertDialog;
private AlertDialog.Builder alertBuilder;
String userType = "V";
String spaces = "\u0020\u0020\u0020\u0020";
Calendar time;
MessageReceived msg;
private RealTime realTime;
private final Context mContext = this;
private boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showProgressDialog();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
obj = (AppController) getApplicationContext();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
lblTyping = (TextView) findViewById(R.id.lblTyping);
txtChatMessage = (EditText) findViewById(R.id.txtChatMessage);
txtChatMessage.setOnKeyListener(this);
txtChatMessage.addTextChangedListener(this);
btnSendChat = (Button) findViewById(R.id.btnSendChat);
btnSendChat.setOnClickListener(this);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertBuilder = new AlertDialog.Builder(this);
lstChatLog = (ListView) findViewById(R.id.lstChatLog);
listAdapter = new ArrayAdapter<String>(ChatActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setHeight(20);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
return view;
}
};
Intent intent = new Intent();
intent.setClass(mContext, RealTime.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
IntentFilter filter = new IntentFilter("Connect");
filter.addAction("RecMsg");
LocalBroadcastManager.getInstance(ChatActivity.this).registerReceiver(mMessageReceiver, filter);
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().toString().equals("Connect")) {
msg = (MessageReceived) intent.getExtras().getParcelable("msg");
if (msg == null || msg.Message == null)
return;
listAdapter.add(msg.Destiny + "" + msg.CurrentTime + " : " + msg.Message);
lstChatLog.setAdapter(listAdapter);
realTime.SendToSpecific(msg.Sender, "Hi !", userType, obj.getRiderId(), obj.getDriverId());
hideProgressDialog();
}
else
if (intent.getAction().toString().equals("RecMsg")) {
msg = (MessageReceived) intent.getExtras().getParcelable("msg");
if (msg == null || msg.Message == null)
return;
if (msg.Message.equals("*0.+9=&!*#_&1|8%digi")) {
lblTyping.setVisibility(View.VISIBLE);
}
else
if (msg.Message.equals("*0.+9=&!*#_&1|8%"))
{
lblTyping.setVisibility(View.INVISIBLE);
}
else
{
lblTyping.setVisibility(View.INVISIBLE);
listAdapter.add(msg.Sender + "" + msg.CurrentTime + " : " + msg.Message);
lstChatLog.setAdapter(listAdapter);
mp = MediaPlayer.create(ChatActivity.this, R.raw.notify);
mp.setLooping(false);
mp.setVolume(100, 100);
mp.start();
}
}
}
};
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
RealTime.LocalBinder binder = (RealTime.LocalBinder) service;
realTime = binder.getService();
mBound = true;
realTime.Connect(obj.getRiderName(), userType, obj.getRiderId(), obj.getLatitudeRider(), obj.getLongitudeRider(), obj.getDriverId(), obj.getVehicieId());
hideProgressDialog();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onStop() {
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
public void SendToSpecific(String sender, String message, String userType, long userId, long operatorId) {
realTime.SendToSpecific(sender, message, userType, userId,operatorId);
if (!message.equals("*0.+9=&!*#_&1|8%digi") && !message.equals("*0.+9=&!*#_&1|8%"))
{
time = Calendar.getInstance();
listAdapter.add(spaces + sender + " " + "(" + time.get(Calendar.HOUR) + ":" + time.get(Calendar.MINUTE) + ")" + " : " + message);
lstChatLog.setAdapter(listAdapter);
txtChatMessage.setText("");
}
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_ENTER) {
if (txtChatMessage.getText().length() > 0)
{
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.
INPUT_METHOD_SERVICE);
if (this.getCurrentFocus() != null)
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
SendToSpecific(obj.getRiderName(), txtChatMessage.getText().toString(), userType, obj.getRiderId(), obj.getDriverId());
}
}
return false;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (txtChatMessage.getText().toString().length() > 0) {
if (txtChatMessage.getText().length() == 1) {
SendToSpecific(obj.getRiderName(), "*0.+9=&!*#_&1|8%digi", userType, obj.getRiderId(), obj.getDriverId());
}
} else {
SendToSpecific(obj.getRiderName(), "*0.+9=&!*#_&1|8%", userType, obj.getRiderId(), obj.getDriverId());
}
}
#Override
public void afterTextChanged(Editable s) {
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSendChat:
if (txtChatMessage != null && txtChatMessage.getText().length() > 0) {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.
INPUT_METHOD_SERVICE);
if (this.getCurrentFocus() != null)
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
SendToSpecific(obj.getRiderName(), txtChatMessage.getText().toString(), userType, obj.getRiderId(), obj.getDriverId());
}
break;
}
}
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}
#Override
protected void onDestroy() {
try {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.
INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null)
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
mMessageReceiver.clearAbortBroadcast();
Intent i = new Intent(this, MenuPageActivity.class);
obj.setLastActivity("Chat");
startActivity(i);
return true;
}
public void ShowAlert() {
hideProgressDialog();
if (resultRequest)
errorMessage = "Internet is not working";
alertBuilder.setTitle("Alert");
alertBuilder.setMessage(errorMessage);
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
alertDialog = alertBuilder.create();
alertDialog.show();
errorMessage = "";
resultRequest = true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
b) Realtime.class
package util;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.util.concurrent.ExecutionException;
import br.com.yourapp.model.MessageReceived;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
public class RealTime extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler;
private final IBinder mBinder = new LocalBinder();
public RealTime() { }
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
startSignalR();
return mBinder;
}
public class LocalBinder extends Binder {
public RealTime getService() {
return RealTime.this;
}
}
public void Connect(String userName, String userType, long userId, double latitude, double longitude, long driverId, long vehicleId) {
mHubProxy.invoke("Connect", userName, userType, userId, latitude, longitude, driverId, vehicleId);
}
public void SendMessageToGroup(String userName, String userGroup, String userType, long userId, double latitude, double longitude, long vehicleId, short option)
{
mHubProxy.invoke("SendMessageToGroup", userName, userGroup, userType, userId, latitude, longitude, vehicleId, option);
}
public void SendToSpecific(String sender, String message, String userType, long userId, long operatorId)
{
mHubProxy.invoke("SendToSpecific", sender, message, userType, userId, operatorId);
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
mHubConnection = new HubConnection("http://webapi.com");
mHubProxy = mHubConnection.createHubProxy("ChatHub");
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
Log.e("SimpleSignalR", e.toString());
return;
}
mHubProxy.on("onConnected",
new SubscriptionHandler1<MessageReceived>() {
#Override
public void run(final MessageReceived msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent("Connect");
intent.putExtra("msg", msg);
LocalBroadcastManager.getInstance(RealTime.this).sendBroadcast(intent);
}
});
}
}
, MessageReceived.class);
}
}
mHubProxy.on("ReceivedMessageServer",
new SubscriptionHandler1<MessageReceived>() {
#Override
public void run(final MessageReceived msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent("RecMsg");
intent.putExtra("msg", msg);
LocalBroadcastManager.getInstance(RealTime.this).sendBroadcast(intent);
}
});
}
}
, MessageReceived.class);
}

App enters infinite loop trying to connect to HC-06, but no loop is present

My application enters an infinite loop when I press the Connect button to connect to an HC-06 Bluetooth module (Arduino shield). However, there are no loops anywhere in the code when the button is pressed.
package dleedesign.dubcommunicationstestapp;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.Set;
/**
* Created by Chris on 7/24/2016.
*/
public class FirstFragment extends Fragment {
View myView;
public final String TAG = "Main";
private Bluetooth bt;
public Button sendCommand;
public Button send;
public TextView msgReceived;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.first_layout, container, false);
sendCommand = (Button) myView.findViewById(R.id.sendCommand);
sendCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
connectService();
}
});
send = (Button) myView.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBtCommand("1");
}
});
msgReceived = (TextView) myView.findViewById(R.id.msgReceived);
msgReceived.setText("Ready to connect");
bt = new Bluetooth(new MainActivity(), mHandler);
return myView;
}
public void sendBtCommand(String msg)
{
bt.sendMessage(msg);
}
public void connectService()
{
try {
msgReceived.setText("Connecting...");
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter.isEnabled())
{
bt.start();
bt.connectDevice("HC-06");
Log.d(TAG, "Btservice started- listening");
msgReceived.setText("Connected!");
}
else
{
Log.w(TAG, "Btservice started - bluetooth is not enabled, requesting enable...");
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
msgReceived.setText("Bluetooth not enabled, requested for enable");
}
} catch (Exception e) {
Log.e(TAG, "Unable to start bluetooth", e);
msgReceived.setText("Unable to connect: " + e);
}
}
private final Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case Bluetooth.MESSAGE_STATE_CHANGE:
Log.d(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
break;
case Bluetooth.MESSAGE_WRITE:
Log.d(TAG, "MESSAGE_WRITE");
break;
case Bluetooth.MESSAGE_READ:
Log.d(TAG, "MESSAGE_READ");
break;
case Bluetooth.MESSAGE_DEVICE_NAME:
Log.d(TAG, "MESSAGE_DEVICE_NAME " + msg);
break;
case Bluetooth.MESSAGE_TOAST:
Log.d(TAG, "MESSAGE_TOAST " + msg);
break;
}
}
};
}
For some reason, this problem just suddenly appeared when I tried to employ a loop to keep trying to connect while the connection is not established. I removed that code, but could it still be there somewhere?
Have you overridden the fragment's onActivityResult method?
If not, try overriding it and calling connectService() inside of it, by adding this to your fragment:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
connectService()
}

RTMP android aftek

I am trying to implement the library from http://www.aftek.com/afteklab/aftek-RTMP-library.shtml
to stream live video from a red5 server.
On the server i am using the simpleBroadcaster and i want to stream it to the android phone.
my code:
package com.cu.reader;
import java.nio.channels.FileChannel;
import java.util.Map;
import com.al.rtmp.client.RtmpClient;
import com.al.rtmp.client.RtmpStream;
import com.al.rtmp.client.RtmpStreamFactory;
import com.al.rtmp.client.data.MetaData;
import com.al.rtmp.client.data.RTMPData;
import com.al.rtmp.client.data.VideoCodec;
import com.al.rtmp.message.Metadata;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class StreamreaderActivity extends Activity implements RtmpClient {
RtmpStream stream = null;
Boolean connected = false;
String server = "rtmp://216.224.181.197/oflaDemo/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
stream = RtmpStreamFactory.getRtmpStream();
stream.setClient(this);
stream.connect(server);
}
#Override
public void streamCreated() {
Log.i("stream","Connected!");
connected = true;
stream.setPlayName("red5StreamDemo");
stream.play();
}
#Override
public byte[] getWriteData(int length) {
// TODO Auto-generated method stub
return null;
}
#Override
public void invoke(String arg0, Object... arg1) {
// TODO Auto-generated method stub
;
}
#Override
public void onDataReceived(RTMPData rtmpData) {
MetaData metaData = rtmpData.getMetaData();
VideoCodec vc = metaData.getVideoCodec();
}
#Override
public void onError(Exception ex) {
Log.e("ClientException", " Some exception occurred." + ex.getMessage());
ex.printStackTrace();
}
#Override
public void onMetaDataReceived(Map map) {
Log.i("code","METADATA:" + map);
}
#Override
public void onResult(String method, Object... arg1) {
Log.i("result","METADATA:" + method);
}
#Override
public void onStatus(String code) {
Log.i("code",code);
}
}
i am always receiving NetStream.Play.StreamNotFound in onStatus function.
Thank you
You get NetStream.Play.StreamNotFound error becouse such stream doesnt exist on red5 application.
I made quick as3 test to check:
package {
import flash.display.Sprite;
import flash.events.AsyncErrorEvent;
import flash.events.IOErrorEvent;
import flash.events.NetStatusEvent;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
public class LearnWowzaClient extends Sprite {
private var nc:NetConnection;
private var video:Video = new Video();
public function LearnWowzaClient() {
nc = new NetConnection();
nc.client = this;
nc.addEventListener(NetStatusEvent.NET_STATUS, onNet);
nc.connect("rtmp://216.224.181.197/oflaDemo/");
}
private function onNet(event:NetStatusEvent):void {
trace(event);
trace(event.info.code);
switch (event.info.code) {
case "NetConnection.Connect.Success":
tryPlayStream();
break;
}
}
private function tryPlayStream():void {
trace("playStream");
var ns:NetStream = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
ns.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAsyncError);
ns.play("red5StreamDemo");
video.attachNetStream(ns);
}
public function onBWCheck(parameter:Object = null):void {
trace("onBWCheck p=" + parameter);
}
public function onBWDone(parameter:Object = null):void {
trace("onBWDone p=" + parameter);
}
private function onIOError(event:IOErrorEvent):void {
trace("onIOError");
}
private function onAsyncError(event:AsyncErrorEvent):void {
trace("onAsyncError");
}
private function onNetStatus(event:NetStatusEvent):void {
trace("onNetStatus ", event.info.code);
}
}
}
I also get NetStream.Play.StreamNotFound error.
Can you show red5 application code?
The stream does not exist, correct. But why? Probably one or two reasons: you have not created a live broadcast stream and 2) because you are using the wrong scope. Unless you configure it differently by hand (which is unlikely), use the 'live' broadcaster scope, which is in /live.
Thus, publish to rtmp://216.224.181.197/live/red5StreamDemo and to subscribe to the exact same mrl, in this example rtmp://216.224.181.197/live/red5StreamDemo. NOTE: for this to work, you need to create a 'live' stream and feed it to your RED5 server. You can use avconv (aka ffmpeg) to create an rtmp feed.

Categories

Resources