I was recently trying to connect to a FTP server via a mobile application.
I'm able to connect to my server and check if it's connected (which it is).
Next thing is to login with a username and password following with a passive mode setup. Last thing I did was get the reply code from the server, but when my application is running, my screens goes black. When I reopen my application it says "recv failed: ECONNREST (Connection reset by peer)" as the error message I output. Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ftpClient = new FTPClient();
textView = (TextView)findViewById(R.id.textView_id);
textView2 = (TextView)findViewById(R.id.textView2_id);
textView3 = (TextView)findViewById(R.id.textView3_id);
textView4 = (TextView)findViewById(R.id.textView4_id);
textView5 = (TextView)findViewById(R.id.textView5_id);
try{
ftpClient.connect(ip, port);
boolean connectSucces = ftpClient.isConnected();
ftpClient.login(userName,passWord);
ftpClient.enterLocalPassiveMode();
ftpClient.getReply();
int connectionMode = ftpClient.getDataConnectionMode();
if(connectionMode == ftpClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
textView.setText("Connected: " + connectSucces + " ConnectionMode: " + connectionMode);
}
}catch(Exception e){
textView.setText(e.getMessage());
}
}
Am I missing something?
I believe it's the call to getReply() that deadlocks your code.
You didn't send any command to which the server should reply, so the client waits for the response until it or the server times out.
The latter happened probably, that's why the connection was closed/reset by the server.
You generally do not call getReply() yourself. In most cases it's called internally by the FTPClient for you:
Only use this method if you are implementing your own FTP client or if you need to fetch a secondary response from the FTP server.
While I have no experience with Android development, from the symptoms and your code, I assume you connect to the FTP server from a GUI thread, what is rather a bad practice. That would explain why the screen goes blank while you wait.
Related
public void connect() {
final String msg = "";
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
s = new Socket("192.168.1.3", 1337);
textView.setText("Connection acquired");
out = s.getOutputStream();
output = new PrintWriter(out);
output.println(msg);
textView.setText("message sent : " + msg.length());
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
I am using the above code to connect to desired IP [192.168.1.3]... I have created another program at the other end... The problem is that the IP sometimes changes to 192.168.1.4 or 192.168.1.6... and when I use another network it changes to 192.168.43.2... now due to this I have to go every time into the code and change it manually....
Is there any function or any other thing that might search for IPs available then check if desired port exists and then connect... Thanks in advance
That's why DNS names exist. If you use an IP address, you have to use that exact address. If you use DNS, you do a name->IP lookup. Get a dynamic DNS provider and use that to give your server a name.
You really do not want to start port scanning to find open ports. You will be treated as an attacker and kicked off the network, because you really would be doing something attackers do.
I have made a basic nodejs server that console logs when a user connects to the server. i am using socket io for this because i wanna make a chat application. On my android side im trying to create a connection to this local server but i never get the console log when i try and socket.connected stays on false. also never get a error or something when trying to connect
I have tried some examples from the internet. i got 1 example working deleted everything that i didnt use and it still works. i copy paste from that example to my own project and still didn't work.
This is the example i used.
Here is the code of my project
Node JS:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Android:
public class MainActivity extends Activity {
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatApplication app = (ChatApplication) getApplication();
socket = app.getSocket();
socket.connect();
}
}
ChatApplication class:
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.0.109:3000");
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
public Socket getSocket() {
return mSocket;
}
}
Android Studio emulator usually prevents localhost connections, I'm not sure if this happened in your case, but it has happened to me. Try popping out your Logcat in Android Studio and see if you can find something that indicates that the localhost connection got denied.
Not sure if this is it, but you should check.
Trying to implement a simple UDP Client/Server datagram between an AndroidStudio-Java application as a client, to a Visual Studio C# Server. I am completely sure of the server side being working.
Here is a UDP Client and on a ButtonClick a UDP message should be sent to the localhost on port 15000 "for now".
my StackTrace popped the Android.os.NetworkOnMainThreadException Error. I found here that I can use an easy solution which is to import StrictMode and set a new policy to permitAll(). However still my application couldn't work and literally nothing happens on ButtonClick "No Exception to trace + No received message" and here is my code:
ButtonOne.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
TextView TextOne = (TextView) findViewById(R.id.TestText);
TextOne.setText("Hi");
String host = "127.0.0.1"; // localhost
int port = 15000;
String message = "Test";
DatagramSocket dsocket = null;
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
// Get the Internet address of the specified host
InetAddress address = InetAddress.getByName(host);
// wrap a packet
DatagramPacket packet = new DatagramPacket(
message.getBytes(),
message.length(),
address, port);
// Create a datagram socket, send the packet through it, close it.
dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
Then I found here here that it's strongly not recommended to use StrictMode and that I need to use AsyncTask. However on Android Documentation it says "AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)" which I don't get because each time I add Async within MainActivity class I get errors and it's frustrating..
Is't okay to use StrictMode for this simple task? If yes, why it's not working? If No, can anyone tell me please how to import AsyncTask into this piece of code? and should I use Params, Progress, Result functions??
Since your packet is send and forget and you do not monitor its progress or do something at its end, you do not need async task. You need to start network activity in a new thread. The code is below, may have minor compilation issues since I do not have access to one right now.
ButtonOne.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
TextView TextOne = (TextView) findViewById(R.id.TestText);
TextOne.setText("Hi");
String message = "Test";
Thread networkThread = new Thread() {
String host = "127.0.0.1"; // localhost
int port = 15000;
DatagramSocket dsocket = null;
public void run() {
try {
// Get the Internet address of the specified host
InetAddress address = InetAddress.getByName(host);
// wrap a packet
DatagramPacket packet = new DatagramPacket(
message.getBytes(),
message.length(),
address, port);
// Create a datagram socket, send the packet through it, close it.
dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
} catch (Exception e) {
e.printStackTrace();
}//catch
}//run
};// Networkthread
networkThread.start();//networkThread.start()
}//onClick
}//onClickListener
);//setOnClickListener
I'm developing an Android app using Apache Mina for network IO. Non-SSL connections (reading, writing) work fine, but as soon as I add an SSL filter things stop working.
I also tried pure SSL sockets and they work fine.
This is my Mina connection code (in a separate networking thread):
IoConnector connector = new NioSocketConnector();
connector.getSessionConfig().setReadBufferSize(2048);
SocketSessionConfig cfg = (SocketSessionConfig)connector.getSessionConfig();
cfg.setTcpNoDelay(true);
SslContextFactory f = new SslContextFactory();
f.setTrustManagerFactory(new BogusTrustManagerFactory());
f.setProtocol("SSL");
try {
filter = new SslFilter(f.newInstance(), true);
} catch (Exception e) {
Log.d(TAG, "Exception: ", e);
return;
}
filter.setUseClientMode(true);
connector.getFilterChain().addLast("sslFilter", filter);
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("ASCII"))));
connector.setHandler(new MinaClientHandler());
ConnectFuture future = connector.connect(new InetSocketAddress("10.0.1.9", 7072));
future.awaitUninterruptibly();
if (!future.isConnected())
{
Log.d(TAG, "not connected, return");
return;
}
IoSession session = future.getSession();
session.getConfig().setUseReadOperation(true);
session.getCloseFuture().awaitUninterruptibly();
//System.out.println(session.read().getMessage());
Log.d(TAG, "after writting");
connector.dispose();
In my IoHandlerAdapter I have the following override:
#Override
public void sessionOpened(IoSession session)
{
session.write(IoBuffer.wrap(data)); // byte array
}
Not my actual code, but it reproduces the problem.
On the server side I see that the connection is accepted an the handshake succeeds. But on the client side nothing is sent over the socket. I have tried the same code in a desktop Java application and it also works.
Also if I move the write call just after IoSession session = future.getSession(); the same thing happens.
Has anyone had similar issues? Are there known issues with Mina on Android? Am I missing some session config options?
Since normal SSL sockets work, that is a workaround, but I would rather not rewrite all my networking code.
please excuse my writing errors...
I'm using NetBeans to run a homemade server and a client, and it all works fine. As I said before, I'm using "Socket" on my client, and "ServerSocket" on my sv. I'm also using JDBC Mysql in the server.
The problem starts when I generate both java files in their distributable folders and use them. The client sends information to the server (it starts with .getOutputStream() and .getInputStream(), then .flush() ), but the server doesn't receive any message. I tried seeing where it stops and it's in
clients[i] = new Client (server.accept(), i);
The crazy thing happens when I try executing my server from NetBeans and the client from my desktop... It works! So the server must be the problem. I'm also using an opened UDP port, and i'm looking for the IP of the server on 192.168.0.10 (which is my computer, in LAN).
I hope someone can help me, thanks in advance!
Here I paste my code, i'm sorry some variables are in spanish:
public ServidorMultiCliente() {
super("Servidor MultiCliente");
initComponents();
try{
servidor = new ServerSocket( 500, maxNumberClients);
}catch(IOException excepcion){
excepcion.printStackTrace();
System.exit(1);
}
serverWriteBox.append("Server iniciated, waiting for connections..."); }
I run these, from the Server:
public void ejecutar(){
clientsAcceptor.start();
messagesListener.start(); }
Where clientsAcceptor is:
private class aceptadorClientes extends Thread{
public void run(){
for( int i = 1; i < maxNumberClients; i++ ){
try{
clientes[i] = new Cliente (servidor.accept(), i); // **Here it stops**
// It never reaches here... (without using NetBeans)
clientes[i].start();
clientes[i].aceptado = true;
}catch(IOException excepcion){
excepcion.printStackTrace();
}
}
That's how I accept clients in different threads. I make the same thing with messageListener, which is a new thread for every new client. It's in a loop, always listening. And here I paste my executable Client, which is different from the Cliente class I was using in ServidorMultiCliente:
public Cliente(){
}
public Cliente(String host){
this.host = host;
this.executeConnection();
}
public void executeConnection(){
int connect = 0;
try {
cliente = new Socket(InetAddress.getByName(host), 500);
conectar = 1;
} catch (IOException ex) {
conectar = 0;
this.ejecutarConexion();
}
if(conectar == 1){
obtainFlows();
}
}
private void obtainFlows(){
try{
output= new ObjectOutputStream( cliente.getOutputStream());
output.flush(); // Here I should be "connected"
input = new ObjectInputStream(cliente.getInputStream());
} catch(IOException ex){
this.initiateDisconnection();
}
sendFlows("I'm connected!");
new messageListener().start(); // This is a thread
}
ServerSocket#accept is a blocking call. It listens to a port and returns a Socket when a client connects. You don't show very much of your server logic but it seems you put clients in an array so you obviously want to support more than one client. You don't show if your Client class starts a thread and returns immediatly.
You should have a server loop that just listens to a server socket and creates clients after it retrieved a client socket. Even if you do this in your Client constructor (I can't tell without the code) it is not a very good place for this and seriously hinders debugging.
If you don't start threads for your clients this would explain a server that "stops" (if "stops" means "blocks" and not "crashes"). See "Writing the Server Side of a Socket" in the Java Tutorial for a detailed explanation.
I can't think of why it behaves different when started via Netbeans. A little bit more of code context is needed.