I am following a quick guide from Smack Documentation, for me to connect my asmack xmpp client with openfire xmpp server. But unfortunately, there a exception errors that I got from following the codes on smack documentation.
Since that I am not actually using smack but instead I am using asmack (smack version for android), I read from here that I should call SmackAndroid.init(Context)in order to initialize Smack on Android or Smack won't work as expected.
I aslo build add and dnsjava library, for me to execute this single line of code SmackAndroid.init(Context). I Thought that these steps will solve my problem upon connecting asmack client with openfire server but its not.
Here is my code:
public class MainActivity extends Activity {
public static final String HOST = "Kirbys-Mac-mini.local";
public static final int PORT = 5222;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ConnectToServer().execute();
}
private class ConnectToServer extends AsyncTask <Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
SmackAndroid.init(MainActivity.this);
boolean isConnected = false;
ConnectionConfiguration config = new ConnectionConfiguration(HOST, PORT);
XMPPConnection conn2 = new XMPPTCPConnection(config);
try {
conn2.connect();
isConnected = true;
}
catch (IOException e){
Log.e("XMPPIOExceptionj", e.toString());
} catch (SmackException e){
Log.e("XMPPSmackException", e.toString()+" Host:"+conn2.getHost()+"Port:"+conn2.getPort());
} catch (XMPPException e){
Log.e("XMPPChatDemoActivity", "Failed to connect to "+ conn2.getHost());
Log.e("XMPPChatDemoActivity", e.toString());
}
return null;
}
After I run the application, Errors will show up in my logcat because there is something wrong happened while connecting to my server. These are the error that was catched by the exception:
11-26 04:24:19.783: E/XMPPSmackException(3964): org.jivesoftware.smack.SmackException$ConnectionException Host:nullPort:0
I don't now why is this happening to my app. Even the way that I setup my openfire is on default and I also use its embedded database. Please help me with my problem.
Related
I have trouble with connecting to a local web interface (192.168.10.13:3671) that are connected to my KNX network from the emulator/phone in Android Studio.
I've tried to connect to the same web interface with a already developed app called KNXwizard and that works, but I see in the code that that app uses AsyncTask.
Always getting this error: Error creating KNXnet/IP tunneling link: tuwien.auto.calimero.KNXException: connecting from /192.168.163.198:3671 to /192.168.10.13:3671: socket failed: EPERM (Operation not permitted)
I've checked this posts
Socket failed 1
Socket failed 2
Tried everything there, added permissions to my AndroidManifest.xml, uninstalled, used physical phone etc. But nothing works.
It could be my code, I've tried searching for an alternative method for AsyncTask. So it could be that the code is written wrong. Hope someone could help me out.
MainActivity:
public class MainActivity extends AppCompatActivity {
private static InetSocketAddress local = new InetSocketAddress("192.168.163.198", 3671);
private static InetSocketAddress server = new InetSocketAddress("192.168.10.13",
KNXnetIPConnection.DEFAULT_PORT);
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
ExecutorService executorService = Executors.newSingleThreadExecutor();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executorService.execute(new Runnable() {
#Override
public void run() {
//doInBackground
System.out.println("This example establishes a tunneling connection to the KNXnet/IP server " + server);
// A KNX tunneling link supports NAT (Network Address Translation) if required.
// We also indicate that the KNX installation uses twisted-pair (TP) medium, with TP1 being the most common.
// KNXNetworkLink is the base interface implemented by all supported Calimero links to a KNX network.
try (KNXNetworkLink knxLink = KNXNetworkLinkIP.newTunnelingLink(local, server, false, TPSettings.TP1)) {
System.out.println("Connection established to server " + knxLink.getName());
System.out.println("Close connection again");
} catch (KNXException | InterruptedException e) {
// KNXException: all Calimero-specific checked exceptions are subtypes of KNXException
// InterruptedException: longer tasks that might block are interruptible, e.g., connection procedures. In
// such case, an instance of InterruptedException is thrown.
// If a task got interrupted, Calimero will clean up its internal state and resources accordingly.
// Any deviation of such behavior, e.g., where not feasible, is documented in the Calimero API.
System.out.println("Error creating KNXnet/IP tunneling link: " + e);
}
}
});
}
});
}
I figured it out.
It was a stupid mistake with the IP address, should have seen that before. I just change the IP address to that I have on the phone I was connected to (192.168.10.15).
Is there a way to create a SOCKS-5 proxy server on an unrooted android device? Why does it require root? Can I make my own android application that will create a server on my device and use this server as proxy on my compluter, all this without rooting the device?
UPDATE: I came to using this library to try to create a proxy server. I downloaded all files, but added only main .jar file to the project dependencies in AndroidStudio. There I am trying to start the server from a runnable in a service. Here is the service code:
public class ProxyService extends Service
{
private static boolean running = false;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
ServerAuthenticatorNone auth = new ServerAuthenticatorNone();
ProxyServer server = new ProxyServer(auth);
Run(server); //runnable is needed because if I start service from
//this thread it throws a network on main thread exception
return START_STICKY;
}
private void Run(ProxyServer server) {
if (running)
return;
final ProxyServer serverFinal = server;
running = true;
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Log.i("DEBUG", "tick " + running);
serverFinal.start(1080);
Log.i("DEBUG", "proxyServer started at port 1080");
running = true;
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
running = false;
}
}
}
}).start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
When I run this code on my Xiaomi Redmi Note 2 unrooted device, I get the following logs:
07-26 16:48:18.097: I/DEBUG(19766): tick true
07-26 16:48:18.099: I/XiaomiFirewall(1211): firewall pkgName:com.socks.server, result:0
And when I check proxy using this website I get nothing.
I think I should have configured the server somehow, but it is done using external .properties file that is outside of the .jar and I do not know how to link them in an AndroidStudio project.
I also suspect that even these actions require superuser(root) to prevent Xiaomi firewall from refusing me in starting the server.
Any advice?
I have started developing live streaming using kurento media server. I have Installed kurento media server in Ubuntu 14.04TLS. It gets successfully Installed and also started successfully.
I have used STUN server, I have uncommented these two lines
stunServerAddress=<stun_ip_address>
stunServerPort=<stun_port>
And used IP, PORT as follows: 173.194.66.127:19302
.After doing all these thing I started kurento media server and it gets started.
Now I create Android native application by implementing RoomListener Interface.
Here is the Code to connect with Kurento Media Server.
public class MainActivity extends AppCompatActivity implements RoomListener {
private LooperExecutor executor;
private static KurentoRoomAPI kurentoRoomAPI;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
executor = new LooperExecutor();
executor.requestStart();
String wsRoomUri = "wss://173.194.66.127:19302/room";
kurentoRoomAPI = new KurentoRoomAPI(executor, wsRoomUri, this);
kurentoRoomAPI.connectWebSocket();
}
#Override
public void onRoomResponse(RoomResponse response) {
Log.d(TAG, "Response");
}
#Override
public void onRoomError(RoomError error) {
Log.d(TAG, "Error: " + error.toString());
}
#Override
public void onRoomNotification(RoomNotification notification) {
Log.d(TAG, "Notification Received");
}
#Override
public void onRoomConnected() {
Log.d(TAG, "Connected");
}
#Override
public void onRoomDisconnected() {
Log.d(TAG, "Room Disconnected");
}
}
But when I run the application, it shows the following error:
Process: com.base.videostreamingkurento, PID: 1880
java.lang.AssertionError: java.net.SocketTimeoutException: failed to connect to /173.194.66.127 (port 19302) after 90000ms
at libcore.io.IoBridge.connect(IoBridge.java:117)
at java.nio.SocketChannelImpl.connect(SocketChannelImpl.java:199)
at org.java_websocket.client.WebSocketClient.interruptableRun(WebSocketClient.java:210)
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:188)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.net.SocketTimeoutException: failed to connect to /173.194.66.127 (port 19302) after 90000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:189)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:115)
It seems that you have a little confusion with your deployment and IPs. You are trying to connect, from your client, to the STUN server. Instead, try setting the IP and PORT where your app server is located in this line
String wsRoomUri = "wss://APP_SERVER_IP:8443/room";
If you can draw that down, you'll see more clearly where everything goes and what should connect to what.
I'm working on a relatively simple login app for a school project. I'm having an issue connecting my app to any URL, local or otherwise. I've added the permission for internet access to the android manifest file.
<uses-permission android:name="android.permission.INTERNET" />
The following code is located in my main activity:
public class MainActivity extends Activity {
private EditText username=null;
private EditText password=null;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.ucidText);
password = (EditText)findViewById(R.id.passText);
login = (Button)findViewById(R.id.button1);
//URL CAN BE ANYTHING, WOULD NORMALLY BE 192.168.1.102
if(isConnectedToServer("<-URL to page on locally hosted server->",10)){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Connection failed", Toast.LENGTH_SHORT).show();
}
}
//Function to determine if connection exists
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url); //<--------- I believe the issue has to do with this line.
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
return false;
}
}
}
This is a stripped down version of my overall project. Everything checks out except the connectivity. I'm running the app from the SDK straight on my phone (Moto X). Any suggestions?
You got the android.os.NetworkOnMainThreadException because you perform your network request on the main thread. You should not do that because you will block the main thread. Instead, you can start a new thread to perform your network request, like this:
final Handler handler = new Handler();
new Thread(){
public void run(){
// check network connection here.
handler.post(/* do the toast work in a Runnable as the parameter here*/);
}
}.start();
You should use some protocol in the "url" string.
For example, you can use
"http://serverIP"
in which the serverIP is 192.168.1.102 and the port is default to 80.
We could not use "192.168.1.102" as the url because the protocol could not be ignored for the URL class.
Dont get angry on me please. I have two questions, I think on very similar theme, so I decided to merge them into one. I have my app on android that is using sensors to do some calculations. I am storing there sesults in my database. What i want to do is to send my data from my phone to my desktop app also with a database (on button click).
To be more precise, here is an example: My light sensor reads current light intensity. Lets say it is 1000lux. Now, when I click my button "Send" in my android app, it will send this value to my desktop apps database. That desktop app will read that value and will show it to user.
Is it possible via WIFI? or better via web, so i will not be limited with distance?
How can android manage this kind of communication?
And my second question is, if controlling media player on my PC is similar to what i said.
EDIT:
I did some research and found one Socket tutorial. I tried it exactly like it is there. So i have this in my android app:
public class Client extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
Client myCli = new Client();
try {
myCli.run();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_client, menu);
return true;
}
public void run() throws Exception {
Socket mySkt = new Socket("192.168.1.6", 9999);
PrintStream myPS = new PrintStream(mySkt.getOutputStream());
myPS.println("Hello server");
BufferedReader myBR = new BufferedReader
(new InputStreamReader(mySkt.getInputStream()));
}
}
and this in netBeans:
//Author: WarLordTech
//Website: http://www.youtube.com/user/WarLordTech
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception{
Server myServ = new Server();
myServ.run();
}
public void run() throws Exception{
ServerSocket mySS = new ServerSocket(9999);
Socket SS_accept = mySS.accept();
BufferedReader SS_BF= new BufferedReader(new InputStreamReader
(SS_accept.getInputStream()));
String temp = SS_BF.readLine();
System.out.println(temp);
if (temp!=null) {
PrintStream SSPS = new PrintStream(SS_accept.getOutputStream());
SSPS.println("Got something");
}
}
}
It still isnt workiong. Do I have to set up my network somehow?
You could do it using TCP Sockets. Many languages have implementations for Socket programming so you would "need" to program your desktop app in Java (of course that is always possible!).
Socket Tutorial in Java
This would work over the net and local wifi. You could use other methods for local wifi such as a UDP connection. You'd need to setup a TCP server and make sure you had access etc.
There may be other ways to do this but it's not such a trivial task to do!