socket.io emit data by android application to node.js server - android

I have problem with emiting data by android application to node.js server.
node.js server:
var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(1000);
app.on('connection', function (client) {
client.name = client.remoteAddress + ':' + client.remotePort;
console.log(client.name + ' connected!');
client.on('sensorChanged', function (data) {
console.log(data);
});
});
and it's Android application
private TextView txtView;
private SocketIO socket;
try {
socket = new SocketIO("http://localhost:1000");
socket.connect(this);
} catch (MalformedURLException e1) {
txtView.setText(e1.getMessage());
}
socket.emit("sensorChanged", "asd");
When I start application, server sees my phone, but when I emit event, server dont respond.
Do you have any idea where is the problem?

i did it like
socket.on("new message", new Emitter.Listener() {
#Override
public void call(Object... args) {
JSONObject obj = (JSONObject) args[0];
try {//do stuff here}
catch(Exception){}
}
}

I guess it's code from android application. I will use it, but right now I need emit data from Android app to node server.
I think the problem is in this line:
`socket.emit("sensorChanged", "asd");`
but it looks good.

I did it like:
socket = new SocketIO();
try {
socket.connect("http://chat.socket.io", this);
} catch (MalformedURLException e) {
e.printStackTrace();
}
socket.emit("new message", "hello TEST");
I dont know what result it should give, but I guess I have to be able see my message on http://chat.socket.io . In this case it doesnt work.

I got the same issue and resolved by adding user.
mSocket.emit("add user", "Andhradroid");

Related

Android Socket connects to server but doesn't write anything

I'm currently runing a server on Eclipse(local IP 192.168.1.255, listening to port 4567). A client can connect trought sockets and send messages, that will be printed on the terminal by the server.
Part of the server code is the following:
System.out.println("Client connected: " + clientName);
String line;
while (true){
line = in.nextLine();
System.out.println("STRING RECEIVED: " + line + " FROM " + clientName);
}
where in is the input stream of the client socket.
Part of client code, instead, is:
while(true) {
System.out.print("\nEnter your input: ");
line = stdin.next();
socketOut.println(line);
socketOut.flush();
}
So, in example, a possible output on server terminal with two clients connected is the following:
Client connected: Socket[addr=/192.168.1.225,port=54852,localport=4567]
STRING RECEIVED: Hello FROM Socket[addr=/192.168.1.225,port=54852,localport=4567]
STRING RECEIVED: World FROM Socket[addr=/192.168.1.225,port=54852,localport=4567]
Client connected: Socket[addr=/192.168.1.225,port=54945,localport=4567]
STRING RECEIVED: Hello2 FROM Socket[addr=/192.168.1.225,port=54945,localport=4567]
Everything works well, so i'm now trying to access server trough sockets on a simple app developed on Android Studio. The code is:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackgroundTask().execute();
}
private class BackgroundTask extends AsyncTask {
#Override
protected Object doInBackground(Object[] params) {
try {
Socket socket = new Socket("10.0.2.2", 4567);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println(new String("Hi from Android!"));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
But the output is just
Client connected: Socket[addr=/192.168.1.225,port=55001,localport=4567]
and nothing else.
Any advice about the println doesn't send anything? The program works perfectly on Eclipse on both client/server side, so i guess the problem is on Android. Also, i enabled the Android network permissions, so the connection should work.
Thanks in advance to everybody.
EDIT: solved, i just changed Android client code to:
try {
Socket socket = new Socket("10.0.2.2", 4567);
if (socket.isConnected()) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
String line = new String("Hi from Android!");
out.println(line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You need to either flush the PrintWriter or construct it to auto-flush. It doesn't by default.

Android FTP server authenticates once

I am trying to implement an FTP server in my application using the Apache FTP server library.
The server is up and running and working fine, but only once.
Note: I am using a hardcoded user for now. username: test and password: test
So in order:
App is launched, server is started, lets all FTP clients login.
App is killed by user.
App is started by user and server is started. Replies 530 authentication failed to user logging in with username: test and password: test
After that it responds with 530 authentication failed
My code below for making the server:
public void makePropertiesFile(){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/user.properties");
if(file.exists() == false){
try {
file.createNewFile();
logMessage("user.properties File did not exist, made one");
properties = file;
this.addUsers();
} catch (IOException e) {
e.printStackTrace();
}
}
else {
logMessage("File already exists, no need to recreate");
userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(properties);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
org.apache.ftpserver.ftplet.UserManager userManager = userManagerFactory.createUserManager();
serverFactory.setUserManager(userManager);
}
}
public void addUsers(){
userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(properties);
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
baseUser = new BaseUser();
baseUser.setName("test");
baseUser.setPassword("test");
baseUser.setHomeDirectory(Environment.getExternalStorageDirectory().getAbsolutePath());
baseUser.setEnabled(true);
List<Authority> authorities = new ArrayList<Authority>();
authorities.add(new WritePermission());
baseUser.setAuthorities(authorities);
org.apache.ftpserver.ftplet.UserManager userManager = userManagerFactory.createUserManager();
try {
userManager.save(baseUser);
} catch (FtpException e) {
e.printStackTrace();
logMessage("Could not save User");
}
serverFactory.setUserManager(userManager);
}
public void start(){
serverFactory = new FtpServerFactory();
listenerFactory = new ListenerFactory();
listenerFactory.setPort(port);
serverFactory.addListener("default",listenerFactory.createListener());
ftpServer = serverFactory.createServer();
this.makePropertiesFile();
try {
ftpServer.start();
logMessage("Started FTP server on port: " + port);
} catch (FtpException e) {
e.printStackTrace();
logMessage("Failed to start FTP server on port: " + port);
}
}
see this link http://androidexample.com/FTP_File_Upload_From_Sdcard_to_server/index.php?view=article_discription&aid=98&aaid=120
has a working project FTP with Android app

Android UDP server does not receive packets

I have the following code to receive UDP packets:
public class AsyncReceiveUdp2 extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... f_url) {
int udp=111;
byte[] packet = new byte[2000];
DatagramPacket dp = new DatagramPacket(packet, packet.length);
DatagramSocket ds = null;
try {
ds = new DatagramSocket(udp);
ds.receive(dp);
//...
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
return null;
}
}
I send UDP data to computer from Android device.
Computer immediately sends response as UDP packet.
I save information to my log file on SD.
And I see, that my app stays on the line "ds.receive(dp);" and does not run after it.
I've tested on the Android device against a program on computer.
As I understand it is tricky to receive UDP packets on Emulator.
I could not do it.
Redirect does not work for me as it is described here
Another important issue is to receive all packets, that were sent to the device. Lossless. How to modify the code for that?
Please help! Thanks!
put your receive inside a while(true) loop. When you receive a packet call an if (pkg_received){break;}... or whatever you want to do...
The problem is that you are probably only be receiving one package and you are getting timeout before receiving it.
Code edited and not tested
while(true)
{
byte[] message = new byte[60*1024];
DatagramPacket recv_packet = new DatagramPacket(message, message.length);
try {
socket.receive(recv_packet);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("UDP", "S: Receiving...listening on port " + recv_packet.getPort() );
String rec_str;
rec_str=new String(recv_packet.getData)
Log.d("PACKAGE LENGTH",Integer.toString(recv_packet.getLength()));
}

android asynctask crash when trying to load an heavy page

I'm programming an app with my brother, and today unfortunately, I encountered with a problem.
When the app load a php page via my asynctask class it works fine. but I would like to program this situation: if the remote server is down, or crash, and doesnt display the right page, the application will show error message. but instead, the app crashes =[
I tried to load this page, for example:
http://alonadoni.com/sql3.php
(I want to simulate that there is a problem with the server. the regular page is sql2.php and it works fine when the server works)
When the app try to load this page (sql3.php) , the app crashes.
I did another experiment : I created a file sql3.php, and wrote "aaaaaaaa" in the page, the app doesn't crash in this situation. it downloaded the data "aaaaa". in this case, the app show jsonexecption error.
Unfortunately, I can't get logcat because my old computer can't run emulators, and my phone also can't connect to my computer on developer mode =[ When I try application I create an apk then transfer the file to my phone and install.
my code is:
in OnCreate:
String serverURL = sss() + "sql3.php?imei=" + imei;
new LongOperation().execute(serverURL);
outside OnCreate:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
if (Error != null) {
} else {
try {
JSONObject json = new JSONObject(data[x]);
name = json.getString("name");
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"e" + e, Toast.LENGTH_LONG).show();
}
}
x++;
}
}
DoInBackground of asynctask needs to contain only NON UI work , hence referring to context and performing UI operations in UI thread may cause crash.
You can perform UI operations in postexecute of asynctask.
Hence Removing toast from above code which refers to UI operation will solve your issue

TCPsending crashes the App if server is down

i wrote a Server for our global Leadbord which actually works now.
I can send data to it if it's active. But if it's down my app does not stop. I dont get a solution for it i hope you can help me. Here is the sending:
public void saveToDatabase(LeadboardElement element2) {
final LeadboardElement element = element2;
send = false;
// Need to be a thread! else android blocks it because it could take to
// long to send!
this.thread = new Thread() {
public void run() {
try {
Socket soc = new Socket(Config.TCP_SERVERNAME_IP,
Config.TCP_PORT);
DataOutputStream out = new DataOutputStream(
soc.getOutputStream());
DataInputStream in = new DataInputStream(
new BufferedInputStream(soc.getInputStream()));
// to call the save statement!
out.writeInt(0);
// give the stuff
out.writeUTF(element.getName());
out.writeInt(element.getLevel());
out.writeInt(element.getKillPoints());
// close it
out.close();
in.close();
soc.close();
send = true;
//join at every error
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// start it
thread.start();
// join thread
if (!send) {
boolean retry = true;
while(retry)
try {
this.thread.join();
retry = false;
Log.w(TAG, "sending to server stopped!");
} catch (InterruptedException e2) {
Log.w(TAG, "Thread could not be joined");
}
}
}
I noticed that i need to do it in a thread since API 5 so it works like this. It's called at the end of an Game if the player touches the screen. Everything get stopped and the data is sent to the Server. If hes down it does not work we stuck in the fade to black.
I guess i need something like a timeout. I tried it with a CountDownTimer but this acutally does not solve the problem.
Thanks alot!
Changing the way you initialize the socket, you can set a timeout.
Socket s1 = new Socket();
s1.setSoTimeout(200);
s1.connect(new InetSocketAddress("192.168.1." + i, 1254), 200);
Add a timeout when creating a new Socket

Categories

Resources