Android client server - java

I have done lots of research on this and tried every method out there to get it to work. I have a C# server that accepts communication on the socket 192.168.0.101:18250. I have the following code (below) and it is the main Activity of the app. The way i coded it is that everything is in the onCreate method so the socket should connect as soon as the app is started, but on my server i dont see it connecting. The server is flawless and i assume there is no problem with it. I also tried an app from the market to see if my phone could even manage to connect to the server and from that app it did communicate through the socket just fine. This is the code i threw together in minutes to test out the socket connection, but no matter what i try the socket just wont connect. And none of the exceptions are thrown either!
import java.io.*;
import java.net.*;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;
public class ClientServerTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
InetAddress addr = InetAddress.getByName("192.168.0.101");
int port = 18250;
// This constructor will block until the connection succeeds
Socket socket = new Socket(addr, port);
socket.getOutputStream();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write("Hello World");
wr.flush();
} catch (UnknownHostException e) {
TextView t=(TextView)findViewById(R.id.textView1);
t.setText(t.getText() + e.getMessage() + "\r\n");
} catch (IOException e) {
TextView t=(TextView)findViewById(R.id.textView1);
t.setText(t.getText() + e.getMessage() + "\r\n");
}
}
}

The problem was not in the code, the problem was in the manifest. I had to add this line to the manifest to grant the application permission to open Network Sockets.
<uses-permission android:name="android.permission.INTERNET" />
Hope it helps someone out! :)

Related

Unable to communicate between Android client and Node.js socket.io server

I've looked at many tutorials on this yet none of them seem to work so no idea whether it's the server, client or potentially something on my network that's stopping it I don't know, so I come here for help.
Just for reference this is the tutorial that this is mainly based on: https://socket.io/blog/native-socket-io-and-android/
So this is my server. All it's supposed to do at the moment is detect when a user connects and then detect users sending messages and send them back to all the clients.
index.js
const express = require("express");
const app = express();
const path = require("path");
const server = require("http").createServer(app);
const io = require("socket.io")(server);
server.listen(3000, () => {
console.log("Server listening at 3000");
});
app.use(express.static(path.join(__dirname, "public")));
io.on("connection", (socket) => {
console.log("User connected");
socket.on("new message", (data) => {
console.log("New message" + data)
socket.emit("new message", {
message: data
});
})
});
My Android client is made up of 3 classes. But to try and keep this shorter I'll only include 2 of them as if the problem can be found in these it's fixable in the 3rd.
This is what's launched at the start and simply pressing the button brings you to the main 'chat' part, but on clicking the button the server should log the connection but nothing appears in the console. So I can only assume the socket connection isn't working for some reason. Also you can ignore the nickname, I've not implemented that yet, been trying to get the main part working first.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
private EditText nickname;
private Button enterChat;
private Socket mSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nickname = findViewById(R.id.nickname);
enterChat = findViewById(R.id.enterChat);
ChatApplication app = (ChatApplication) getApplication();
mSocket = app.getSocket();
mSocket.connect();
enterChat.setOnClickListener(v -> {
mSocket.emit("connection");
Intent i = new Intent(MainActivity.this, ChatActivity.class);
i.putExtra("name", nickname.getText().toString());
startActivity(i);
});
}
}
This is just to be able to get the Socket from any other activity.
ChatApplication.java
import android.app.Application;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
//My IPv4 address here
mSocket = IO.socket("http://xxx.xxx.x.xxx:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
Any help appreciated :)
Found the problem, I need to add this to the AndroidManifest.xml
<application
...
android:usesCleartextTraffic="true"
...
</application>

cannot get android app to connect to my server on my local computer

Hi I'm new to android and Im
Trying to get my android app to connect to a my server that is running on my local computer. Im just trying to get the app to send a simple string message to the server first but keep getting an error. From the print out statements i can see that the app terminates as soon as it hits the line with the try in it so i believe there is an issue with creating the client connection. I have also enable Internet,ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE permissions
i tried changing the localhost to InetAddress.getLocalHost() but still wouldn't work
heres my code :
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import static java.net.InetAddress.getLocalHost;
public class MainActivity extends AppCompatActivity{
private Button cam;
private Socket client;
DataOutputStream os;
private String IP = "localhost";
private static final String TAG = "testing";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.activity_main);
cam = (Button) findViewById(R.id.Button_camera);
cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "trying to connect to server");
try {
client = new Socket("My IP address entered", 8080);
Log.v(TAG, "client socket initalised");
String hey = "hey";
os = new DataOutputStream(client.getOutputStream());
Log.v(TAG, "outptu stream created");
os.flush();
Log.v(TAG, "flush");
os.writeBytes(hey);
Log.v(TAG, "written to server");
os.close();
} catch (UnknownHostException e) {
Log.v(TAG, "Unknown error");
Log.v(TAG, e.toString());
} catch (IOException e) {
Log.v(TAG, "IO exception u numpty");
Log.v(TAG, e.toString());
}
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
});
}
}
my code prints out the statement trying to connect to server but doesn't reach any of the other print out statements and my server is still not receiving anything
connect failed: ETIMEDOUT (Connection timed out)
ACTION_DOWN before UnsetPressedState. invoking mUnsetPressedState.run()
I/Choreographer: Skipped 3792 frames! The application may be doing too much work on its main thread.
I believe this is definitely just an issue with your IP, you are obviously giving ti the wrong ip address because everything else is fine. I would recommend either accessing the terminal and using the ifconfig command to find your ip or access your network settings, if your using a mac like I am select network , advance options , select tcp/ip tab and use ipv4 address as the ip address. If that doesn't work try using a different port or checking your firewall setting on your local computer. Hope that helps.
Localhost is the phone itself, not your computer. If on a simulator, localhost is the simulator, not your computer- the simulator doesn't know its a simulator, it has its own IP address. Fix the IP you're using.

Redirect Client in Java-Run Server

I am creating a Java HTTP server that checks to make sure a client is not banned before redirecting to the main server. I have already created everything for the server that is needed, I just don't know how to redirect to another port that is running the main server. Here is my code:
package netlyaccesscontrol;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class AllowedCheck {
public static void main(String[] args) {
String line = null;
try {
FileReader reader = new FileReader("Banned.txt");
BufferedReader buffer = new BufferedReader(reader);
ServerSocket s = new ServerSocket(80);
Socket c = s.accept();
String clientIP = c.getInetAddress().toString();
while ((line = buffer.readLine()) != null) {
if (clientIP == line) {
s.close();
} else {
// redirect to main server here
}
}
} catch (FileNotFoundException ex) {
System.out.println("The banned IP address file does not exist.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The redirection that you are thinking of is something supported by HTTP and the browsers. There's a specific HTTP response code that tells the caller to redirect and a way to specify it.
Raw sockets are a low-level network protocol that is not going to support redirection as you expect. The most you might be able to do is have this program be a proxy and, upon success, push all incoming data/outgoing responses to/from the ultimate server. But what you have here is by no means going to cut it.

How can I test a simple Server -- Client Application on my own machine at home?

I want to test this simpel server-client application on my own machine at home. How can I run this in Eclipse and then see if the other side can see my message. I want to at some point be able to make a chat window that anyone could have on their machine and send messages to anyone that is online that is linked into the chat window.
But first I have to be able to see that I have a connection. Should I install a server on my computer, or someone told me that there was a server already installed on my computer but I just had to have windows turn it on. (Windows 7)
Question: How can I test this client-server on my computer at home?
Code:
Client Side:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JOptionPane;
public class DateClient {
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
Socket s = new Socket(serverAddress, 9090);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Server side:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DateServer {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9090);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
}
Code I want to Add for new message:
out.println("Hello Doug, how are you!);
This will not show in my message box when it shows up on the screen. Is 127.0.0.1 always the IP address that needs to be entered when testing from eclipse or how would I change this around so that I could let the user determine their own IP address.
You can just open two terminals. For the DateClient, just use localhost or 127.0.0.1 as the address. If you really must use Eclipse, then you can run one of the program from Eclipse and the other from a terminal.
You don't need any server.
In Eclipse (assuming your coding is correct), you can run multiple programs (Java files with a main method) simultaneously.
First, say DateServer -> Run As -> Java Application
Next, say DateClient -> Run As -> Java Application
To run this, you don't need any additional server, but Win 7 might ask you for permissions to unblock these programs from accessing the network. You should say yes to these permissions.
If you want to get a feel of separate client and server, this might be better
Keep the DateClient and DateServer in two different projects
Compile both projects as JARs
Open two different DOS consoles and run these two applications in these separate DOS consoles.
Client Side :
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClientSide {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 1234);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello");
} catch (IOException ex) {
System.out.println("Connection failed");
}
}
}
Server Side :
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
public class ServerSide {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(1234);
System.out.println("waiting for connection...");
DataInputStream dis = new DataInputStream(ss.accept().getInputStream());
System.out.println("Successfully Connected\n" + dis.readUTF());
} catch (IOException ex) {
System.out.println("Server Not Started : " + ex);
}
}
}

I have a "could not connect to host" Logcat message while trying to connect to FTP server, what am I doing wrong?

I'm developing an application on Android that connects to a FTP server to upload and download files. To make the connection I'm using the apache commons-net library's FTPClient class based on this and I'm working on Eclipse.
But I get the following message on my Logcat:
07-04 21:11:44.196: D/USB Virtual(14708): Error: could not connect to host ftp://xxx.xxx
The following is my manifest permissions:
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
I'm really lost as to why I can't connect to my FTP server, in the console there're no errors showing. Am I missing something? I would thank any help.
I'm adding the code I'm using to connect to my FTP server:
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
//host is ftp://looner-project.zxq.net
mFTPClient.connect(host);
mFTPClient.connect(InetAddress.getByName(host));
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
Log.d(TAG, "Error: could not connect to host " + host);
}
return false;
}
Things to check...
1. Check your internet connection.
2. Are you giving the Url to the ftp site correct ??
3. If its password protected, are you giving them correctly ??
4. Using command prompt check it. Give the below command to check it.
ftp www.your_ftp_site.com
after the above command you will be prompted for username and password.
I am also attaching my code which i used to upload audio file to the server to make it clear...
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import android.util.Log;
public class MyOwn {
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("www.mysamle.net"); // Its dummy Address
if (con.login("uju495", "Stevejobs!!"))
{
con.enterLocalPassiveMode(); // Very Important
con.setFileType(FTP.BINARY_FILE_TYPE); // Very Important
String data = "/sdcard/Vivekm4a.m4a";
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/Ads/Vivekm4a.m4a", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Categories

Resources