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
Related
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.
I’m developing XMPP client using smack 4.2.3. Using ejabberd as an XMPP server on linux platform.
Using following code to send file:
public static void sendFile(String path, String description){
String sFqdn = currentUser.getFqdn();
if(sFqdn.equals(null)) return;
String node = XmppStringUtils.parseLocalpart(sFqdn);
String domain = XmppStringUtils.parseDomain(sFqdn);
String resource = XmppStringUtils.parseResource(sFqdn);
try {
EntityFullJid fqdn = entityFullFrom(node, domain, resource);
OutgoingFileTransfer transfer = FileTransferManager.getInstanceFor(connection).createOutgoingFileTransfer(fqdn);
transfer.sendFile(new File(path), description);
} catch (SmackException e) {
e.printStackTrace();
} catch (XmppStringprepException e) {
e.printStackTrace();
}
}
and to receive:
if(fileTransferManager == null){
fileTransferManager = FileTransferManager.getInstanceFor(connection);
fileTransferManager.addFileTransferListener(new FileTransferListener() {
#Override
public void fileTransferRequest(final FileTransferRequest request) {
// Accept it
IncomingFileTransfer transfer = request.accept();
try {
transfer.recieveFile(new File(dir_path+request.getFileName()));
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
sometimes it successfully sends a file between users, but most of the time i get this XMPP error:
D/SMACK: RECV (1): <iq xml:lang=‘en’ to=‘bob#domain/122573506394002920791746’ from=‘tom#domain/126676407739368221821682’ type=‘set’ id=‘VdzEA-77’><si xmlns=‘http: //jabber .org/protocol/si’ id=‘jsi_8874207690796615693’ mime-type=‘image/png’ profile=‘http ://jabber .org/protocol/si/profile/file-transfer’><desc>test file</desc></file><feature xmlns=‘http ://jabber .org/protocol/feature-neg’><x xmlns=‘jabber:x:data’ type=‘form’><field var=‘stream-method’ type=‘list-single’><option><value>http ://jabber .org/protocol/bytestreams</value></option><option><value>http ://jabber .org/protocol/ibb</value></option></field></x></feature></iq><r xmlns=‘urn:xmpp:sm:3’/>
D/SMACK: SENT (1): <iq to=‘tom#domain/126676407739368221821682’ id=‘VdzEA-77’ type=‘error’><error type=‘cancel’><service-unavailable xmlns=‘urn:ietf:params:xml:ns:xmpp-stanzas’/></error></iq>
In ejabberd config file I’ve successfully enabled the module “mod_proxy65”
One reason I can think of is that it might happening due to continuous presence changed by the receiver, that changes its resource.
Although I’m keeping the track of presence in Roster’s presenceChanged() method but still no success. I’m wondering if there is any way in smack to connect to server with a static resource?
One more thing, is there any example for HTTP_FILE_UPLOAD (XEP-0363), I can’t find any in smacks official documentation.
After discussion at ignite realtime's forum, I found out that I was hitting a bug.
A work around to this bug is forced in-band byte stream.
Setting FileTransferNegotiator.IBB_ONLY to true did the trick for me.
Please take a look at line 76 in FileTransferNegotiator class as well.
I am trying to connect to dialogic xms server using autobahn WebSockets:
As read I need to add a protocol rtcweb
This is my code :
String uri = "ws://myUrl:port";
WebSocketConnection ws = new WebSocketConnection();;
wsObserver = new WebSocketObserver();
String[] protocols = {"rtcweb"};
try {
ws.connect(new URI(uri), protocols, wsObserver, new WebSocketOptions() );
} catch (WebSocketException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
But when i add the protocol rtcweb I get this onClose; and the connection still didn't open :
Code: CONNECTION_LOST. Reason: WebSockets connection lost
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");
I can't access "ftp server in PC" from "android app" to download file, I used wireless connection.
public void FTP_Download(){
String server = "192.168.1.135";
int port = 21;
String user = "pc1";
String pass = "1551";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Toast.makeText(getBaseContext(), "download starting.",Toast.LENGTH_LONG).show();
// APPROACH #1: using retrieveFile(String, OutputStream)
String remoteFile1 = "i.xml";
File downloadFile1 = new File("sdcard/i.xml");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
Toast.makeText(getBaseContext(), "File #1 has been downloaded successfully.",Toast.LENGTH_LONG).show();
}
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I added internet permission :
<uses-permission android:name="android.permission.INTERNET"/>
Note: I tested app in emulator on PC and all things was OK.
When I tried to access FTP from default browser I can't, but I can from firefox.
any help please
I've had the same issue. If it worked on the emulator and not on the device, there's probably a firewall in your way, or your network isn't allowing the connection because for some reason it's not secure enough. Also make sure your FTP server allows connections from your username and password.